@microsoft/connected-workbooks 2.1.24-beta → 2.1.25

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 (45) hide show
  1. package/README.md +10 -6
  2. package/dist/generators.js +1 -1
  3. package/dist/{GridParser.js → gridParser.js} +18 -8
  4. package/dist/gridUtils.js +58 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/src/generators.js +14 -0
  7. package/dist/src/types.js +28 -0
  8. package/dist/src/utils/arrayUtils.js +46 -0
  9. package/dist/src/utils/constants.js +139 -0
  10. package/dist/src/utils/documentUtils.js +102 -0
  11. package/dist/src/utils/gridUtils.js +103 -0
  12. package/dist/src/utils/htmlUtils.js +19 -0
  13. package/dist/src/utils/index.js +24 -0
  14. package/dist/src/utils/mashupDocumentParser.js +145 -0
  15. package/dist/src/utils/pqUtils.js +100 -0
  16. package/dist/src/utils/tableUtils.js +143 -0
  17. package/dist/src/utils/xmlInnerPartsUtils.js +200 -0
  18. package/dist/src/utils/xmlPartsUtils.js +64 -0
  19. package/dist/src/workbookTemplate.js +7 -0
  20. package/dist/tests/arrayUtils.test.js +65 -0
  21. package/dist/tests/documentUtils.test.js +35 -0
  22. package/dist/tests/gridUtils.test.js +168 -0
  23. package/dist/tests/htmlUtils.test.js +109 -0
  24. package/dist/tests/mashupDocumentParser.test.js +59 -0
  25. package/dist/tests/mocks/PqMock.js +7 -0
  26. package/dist/tests/mocks/index.js +24 -0
  27. package/dist/tests/mocks/section1mSimpleQueryMock.js +18 -0
  28. package/dist/tests/mocks/xmlMocks.js +12 -0
  29. package/dist/tests/tableUtils.test.js +63 -0
  30. package/dist/tests/workbookQueryTemplate.test.js +64 -0
  31. package/dist/tests/workbookTableTemplate.test.js +54 -0
  32. package/dist/tests/xmlInnerPartsUtils.test.js +51 -0
  33. package/dist/types.d.ts +4 -1
  34. package/dist/utils/constants.js +15 -8
  35. package/dist/utils/documentUtils.js +9 -5
  36. package/dist/utils/gridUtils.js +103 -0
  37. package/dist/utils/htmlUtils.js +3 -3
  38. package/dist/utils/index.js +5 -1
  39. package/dist/utils/mashupDocumentParser.js +6 -24
  40. package/dist/utils/pqUtils.js +7 -4
  41. package/dist/utils/tableUtils.js +18 -19
  42. package/dist/utils/xmlInnerPartsUtils.js +11 -9
  43. package/dist/utils/xmlPartsUtils.js +5 -3
  44. package/dist/workbookManager.js +5 -16
  45. package/package.json +3 -2
package/README.md CHANGED
@@ -1,7 +1,6 @@
1
1
  # Connected Workbooks
2
2
  [![Build Status](https://obilshield.visualstudio.com/ConnectedWorkbooks/_apis/build/status/microsoft.connected-workbooks?branchName=main)](https://obilshield.visualstudio.com/ConnectedWorkbooks/_build/latest?definitionId=14&branchName=main)
3
3
  [![License](https://img.shields.io/github/license/microsoft/connected-workbooks)](https://github.com/microsoft/connected-workbooks/blob/master/LICENSE)
4
- [![Snyk Vulnerabilities](https://img.shields.io/snyk/vulnerabilities/github/microsoft/connected-workbooks)](https://snyk.io/test/github/microsoft/connected-workbooks)
5
4
 
6
5
  A pure JS library, Microsoft backed, that provides xlsx workbook generation capabilities, allowing for:
7
6
  1. Fundemental **"Export to Excel"** capabilities for tabular data (landing in a table in Excel).
@@ -31,12 +30,12 @@ workbookManager.downloadWorkbook(blob, "MyTable.xlsx");
31
30
  ```
32
31
 
33
32
  ### 2. Export a table from raw data:
34
- ```
33
+ ```typescript
35
34
  import workbookManager from '@microsoft/connected-workbooks';
36
35
 
37
36
  const grid = {
38
- "promoteHeaders": true,
39
- "data": [
37
+ config: { promoteHeaders:true, adjustColumnNames:true }
38
+ data: [
40
39
  ["Product", "Price", "InStock", "Category", "Date"],
41
40
  ["Widget A", 19.99, true, "Electronics", "10/26/2024"],
42
41
  ["Gizmo B", 9.99, true, "Accessories", "10/26/2024"],
@@ -152,9 +151,14 @@ async function `generateTableWorkbookFromGrid`: `Promise<Blob>`
152
151
  #### Grid
153
152
  |Parameter | Type | Required | Description |
154
153
  |---|---|---|---|
155
- | data | (string | number | boolean)[][] | __required__ | Grid data
156
- | promoteHeaders | boolean | optional | Should first row of gridData be used as the header, defaults to false - generating "Column1", "Column2"...
154
+ | data | (string \| number \| boolean)[][] | __required__ | Grid data
155
+ | config | GridConfig | optional | customizations to Grid handling (see GridConfig)
157
156
 
157
+ #### GridConfig
158
+ |Parameter | Type | Required | Description |
159
+ |---|---|---|---|
160
+ | promoteHeaders | boolean | optional | Should first row of gridData be used as the header, defaults to false - generating "Column1", "Column2"...
161
+ | adjustColumnNames | boolean | optional | Should column names be adjusted to be valid Excel names (Fix duplicates for example), defaults to true
158
162
 
159
163
  #### FileConfigs
160
164
  |Parameter | Type | Required | Description |
@@ -7,7 +7,7 @@ const generateMashupXMLTemplate = (base64) => `<?xml version="1.0" encoding="utf
7
7
  exports.generateMashupXMLTemplate = generateMashupXMLTemplate;
8
8
  const generateSingleQueryMashup = (queryName, query) => `section Section1;
9
9
 
10
- shared ${queryName} =
10
+ shared #"${queryName}" =
11
11
  ${query};`;
12
12
  exports.generateSingleQueryMashup = generateSingleQueryMashup;
13
13
  const generateCustomXmlFilePath = (i) => `customXml/item${i}.xml`;
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
2
4
  Object.defineProperty(exports, "__esModule", { value: true });
3
5
  exports.parseToTableData = void 0;
4
6
  const constants_1 = require("./utils/constants");
7
+ const utils_1 = require("./utils");
5
8
  const parseToTableData = (grid) => {
6
9
  if (!grid) {
7
10
  return undefined;
@@ -12,12 +15,13 @@ const parseToTableData = (grid) => {
12
15
  };
13
16
  exports.parseToTableData = parseToTableData;
14
17
  const parseGridRows = (grid) => {
18
+ var _a, _b;
15
19
  const gridData = grid.data;
16
20
  if (!gridData) {
17
21
  throw new Error(constants_1.gridNotFoundErr);
18
22
  }
19
23
  const rows = [];
20
- if (!grid.promoteHeaders) {
24
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
21
25
  const row = [];
22
26
  for (const prop in gridData[0]) {
23
27
  const cellValue = gridData[0][prop];
@@ -30,19 +34,25 @@ const parseGridRows = (grid) => {
30
34
  const row = [];
31
35
  for (const prop in rowData) {
32
36
  const cellValue = rowData[prop];
33
- row.push(cellValue.toString());
37
+ row.push((_b = cellValue === null || cellValue === void 0 ? void 0 : cellValue.toString()) !== null && _b !== void 0 ? _b : "");
34
38
  }
35
39
  rows.push(row);
36
40
  }
37
41
  return rows;
38
42
  };
39
43
  const generateColumnNames = (grid) => {
40
- if (grid.promoteHeaders) {
41
- return grid.data[0].map((columnName) => columnName.toString());
42
- }
44
+ var _a;
43
45
  const columnNames = [];
44
- for (let i = 0; i < grid.data[0].length; i++) {
45
- columnNames.push(`Column ${i + 1}`);
46
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
47
+ for (let i = 0; i < grid.data[0].length; i++) {
48
+ columnNames.push(`${constants_1.defaults.columnName} ${i + 1}`);
49
+ }
50
+ return columnNames;
51
+ }
52
+ // We are adjusting column names by default.
53
+ if (!grid.config || grid.config.adjustColumnNames === undefined || grid.config.adjustColumnNames) {
54
+ return utils_1.tableUtils.getAdjustedColumnNames(grid.data[0]);
46
55
  }
47
- return columnNames;
56
+ // Get column names and failed if it's not a legal name.
57
+ return utils_1.tableUtils.getRawColumnNames(grid.data[0]);
48
58
  };
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.parseToTableData = void 0;
6
+ const constants_1 = require("./utils/constants");
7
+ const utils_1 = require("./utils");
8
+ const parseToTableData = (grid) => {
9
+ if (!grid) {
10
+ return undefined;
11
+ }
12
+ const columnNames = generateColumnNames(grid);
13
+ const rows = parseGridRows(grid);
14
+ return { columnNames: columnNames, rows: rows };
15
+ };
16
+ exports.parseToTableData = parseToTableData;
17
+ const parseGridRows = (grid) => {
18
+ var _a, _b;
19
+ const gridData = grid.data;
20
+ if (!gridData) {
21
+ throw new Error(constants_1.gridNotFoundErr);
22
+ }
23
+ const rows = [];
24
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
25
+ const row = [];
26
+ for (const prop in gridData[0]) {
27
+ const cellValue = gridData[0][prop];
28
+ row.push(cellValue.toString());
29
+ }
30
+ rows.push(row);
31
+ }
32
+ for (let i = 1; i < gridData.length; i++) {
33
+ const rowData = gridData[i];
34
+ const row = [];
35
+ for (const prop in rowData) {
36
+ const cellValue = rowData[prop];
37
+ row.push((_b = cellValue === null || cellValue === void 0 ? void 0 : cellValue.toString()) !== null && _b !== void 0 ? _b : "");
38
+ }
39
+ rows.push(row);
40
+ }
41
+ return rows;
42
+ };
43
+ const generateColumnNames = (grid) => {
44
+ var _a;
45
+ const columnNames = [];
46
+ if (!((_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders)) {
47
+ for (let i = 0; i < grid.data[0].length; i++) {
48
+ columnNames.push(`${constants_1.defaults.columnName} ${i + 1}`);
49
+ }
50
+ return columnNames;
51
+ }
52
+ // We are adjusting column names by default.
53
+ if (!grid.config || grid.config.adjustColumnNames === undefined || grid.config.adjustColumnNames) {
54
+ return utils_1.tableUtils.getAdjustedColumnNames(grid.data[0]);
55
+ }
56
+ // Get column names and failed if it's not a legal name.
57
+ return utils_1.tableUtils.getRawColumnNames(grid.data[0]);
58
+ };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as workbookManager from "./workbookManager";
2
2
  import { DataTypes } from "./types";
3
- import type { QueryInfo, FileConfigs, Grid } from "./types";
3
+ import type { QueryInfo, FileConfigs, Grid, DocProps } from "./types";
4
4
  export { DataTypes };
5
- export type { QueryInfo, FileConfigs, Grid };
5
+ export type { QueryInfo, FileConfigs, Grid, DocProps };
6
6
  export default workbookManager;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.generateCustomXmlFilePath = exports.generateSingleQueryMashup = exports.generateMashupXMLTemplate = void 0;
6
+ const generateMashupXMLTemplate = (base64) => `<?xml version="1.0" encoding="utf-16"?><DataMashup xmlns="http://schemas.microsoft.com/DataMashup">${base64}</DataMashup>`;
7
+ exports.generateMashupXMLTemplate = generateMashupXMLTemplate;
8
+ const generateSingleQueryMashup = (queryName, query) => `section Section1;
9
+
10
+ shared #"${queryName}" =
11
+ ${query};`;
12
+ exports.generateSingleQueryMashup = generateSingleQueryMashup;
13
+ const generateCustomXmlFilePath = (i) => `customXml/item${i}.xml`;
14
+ exports.generateCustomXmlFilePath = generateCustomXmlFilePath;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.DocPropsAutoUpdatedElements = exports.DocPropsModifiableElements = exports.DataTypes = void 0;
6
+ var DataTypes;
7
+ (function (DataTypes) {
8
+ DataTypes[DataTypes["null"] = 0] = "null";
9
+ DataTypes[DataTypes["string"] = 1] = "string";
10
+ DataTypes[DataTypes["number"] = 2] = "number";
11
+ DataTypes[DataTypes["boolean"] = 3] = "boolean";
12
+ })(DataTypes = exports.DataTypes || (exports.DataTypes = {}));
13
+ var DocPropsModifiableElements;
14
+ (function (DocPropsModifiableElements) {
15
+ DocPropsModifiableElements["title"] = "dc:title";
16
+ DocPropsModifiableElements["subject"] = "dc:subject";
17
+ DocPropsModifiableElements["keywords"] = "cp:keywords";
18
+ DocPropsModifiableElements["createdBy"] = "dc:creator";
19
+ DocPropsModifiableElements["description"] = "dc:description";
20
+ DocPropsModifiableElements["lastModifiedBy"] = "cp:lastModifiedBy";
21
+ DocPropsModifiableElements["category"] = "cp:category";
22
+ DocPropsModifiableElements["revision"] = "cp:revision";
23
+ })(DocPropsModifiableElements = exports.DocPropsModifiableElements || (exports.DocPropsModifiableElements = {}));
24
+ var DocPropsAutoUpdatedElements;
25
+ (function (DocPropsAutoUpdatedElements) {
26
+ DocPropsAutoUpdatedElements["created"] = "dcterms:created";
27
+ DocPropsAutoUpdatedElements["modified"] = "dcterms:modified";
28
+ })(DocPropsAutoUpdatedElements = exports.DocPropsAutoUpdatedElements || (exports.DocPropsAutoUpdatedElements = {}));
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.ArrayReader = void 0;
6
+ class ArrayReader {
7
+ constructor(array) {
8
+ this._array = array;
9
+ this._position = 0;
10
+ }
11
+ getInt32() {
12
+ const retVal = new DataView(this._array, this._position, 4).getInt32(0, true);
13
+ this._position += 4;
14
+ return retVal;
15
+ }
16
+ getBytes(bytes) {
17
+ const retVal = this._array.slice(this._position, bytes ? bytes + this._position : bytes);
18
+ this._position += retVal.byteLength;
19
+ return new Uint8Array(retVal);
20
+ }
21
+ reset() {
22
+ this._position = 0;
23
+ }
24
+ }
25
+ exports.ArrayReader = ArrayReader;
26
+ function getInt32Buffer(val) {
27
+ const packageSizeBuffer = new ArrayBuffer(4);
28
+ new DataView(packageSizeBuffer).setInt32(0, val, true);
29
+ return new Uint8Array(packageSizeBuffer);
30
+ }
31
+ function concatArrays(...args) {
32
+ let size = 0;
33
+ args.forEach((arr) => (size += arr.byteLength));
34
+ const retVal = new Uint8Array(size);
35
+ let position = 0;
36
+ args.forEach((arr) => {
37
+ retVal.set(arr, position);
38
+ position += arr.byteLength;
39
+ });
40
+ return retVal;
41
+ }
42
+ exports.default = {
43
+ ArrayReader,
44
+ getInt32Buffer,
45
+ concatArrays,
46
+ };
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.element = exports.BOM = exports.falseStr = exports.trueStr = exports.maxQueryLength = exports.divider = exports.section1PathPrefix = exports.emptyValue = exports.falseValue = exports.trueValue = exports.pivotCachesPathPrefix = exports.xmlTextResultType = exports.textResultType = exports.application = exports.uint8ArrayType = exports.blobFileType = exports.arrayIsntMxNErr = exports.unexpectedErr = exports.promotedHeadersCannotBeUsedWithoutAdjustingColumnNamesErr = exports.InvalidColumnNameErr = exports.stylesNotFoundErr = exports.EmptyQueryNameErr = exports.QueryNameInvalidCharsErr = exports.QueryNameMaxLengthErr = exports.invalidDataTypeErr = exports.headerNotFoundErr = exports.invalidValueInColumnErr = exports.tableNotFoundErr = exports.queryTableNotFoundErr = exports.templateWithInitialDataErr = exports.formulaSectionNotFoundErr = exports.queryConnectionNotFoundErr = exports.queryAndPivotTableNotFoundErr = exports.queryNameNotFoundErr = exports.emptyQueryMashupErr = exports.base64NotFoundErr = exports.sheetsNotFoundErr = exports.connectionsNotFoundErr = exports.sharedStringsNotFoundErr = exports.docPropsRootElement = exports.docPropsCoreXmlPath = exports.section1mPath = exports.pivotCachesPath = exports.queryTablesPath = exports.workbookXmlPath = exports.queryTableXmlPath = exports.tableXmlPath = exports.sheetsXmlPath = exports.sharedStringsXmlPath = exports.connectionsXmlPath = void 0;
6
+ exports.URLS = exports.defaults = exports.elementAttributesValues = exports.dataTypeKind = exports.elementAttributes = void 0;
7
+ exports.connectionsXmlPath = "xl/connections.xml";
8
+ exports.sharedStringsXmlPath = "xl/sharedStrings.xml";
9
+ exports.sheetsXmlPath = "xl/worksheets/sheet1.xml";
10
+ exports.tableXmlPath = "xl/tables/table1.xml";
11
+ exports.queryTableXmlPath = "xl/queryTables/queryTable1.xml";
12
+ exports.workbookXmlPath = "xl/workbook.xml";
13
+ exports.queryTablesPath = "xl/queryTables/";
14
+ exports.pivotCachesPath = "xl/pivotCache/";
15
+ exports.section1mPath = "Formulas/Section1.m";
16
+ exports.docPropsCoreXmlPath = "docProps/core.xml";
17
+ exports.docPropsRootElement = "cp:coreProperties";
18
+ exports.sharedStringsNotFoundErr = "SharedStrings were not found in template";
19
+ exports.connectionsNotFoundErr = "Connections were not found in template";
20
+ exports.sheetsNotFoundErr = "Sheets were not found in template";
21
+ exports.base64NotFoundErr = "Base64 was not found in template";
22
+ exports.emptyQueryMashupErr = "Query mashup is empty";
23
+ exports.queryNameNotFoundErr = "Query name was not found";
24
+ exports.queryAndPivotTableNotFoundErr = "No such query found in Query Table or Pivot Table found in given template";
25
+ exports.queryConnectionNotFoundErr = "No connection found for query";
26
+ exports.formulaSectionNotFoundErr = "Formula section wasn't found in template";
27
+ exports.templateWithInitialDataErr = "Cannot receive template file with initial data";
28
+ exports.queryTableNotFoundErr = "Query table wasn't found in template";
29
+ exports.tableNotFoundErr = "Table wasn't found in template";
30
+ exports.invalidValueInColumnErr = "Invalid cell value in column";
31
+ exports.headerNotFoundErr = "Invalid JSON file, header is missing";
32
+ exports.invalidDataTypeErr = "Invalid JSON file, invalid data type";
33
+ exports.QueryNameMaxLengthErr = "Query names are limited to 80 characters";
34
+ exports.QueryNameInvalidCharsErr = 'Query names cannot contain periods or quotation marks. (. ")';
35
+ exports.EmptyQueryNameErr = "Query name cannot be empty";
36
+ exports.stylesNotFoundErr = "Styles were not found in template";
37
+ exports.InvalidColumnNameErr = "Invalid column name";
38
+ exports.promotedHeadersCannotBeUsedWithoutAdjustingColumnNamesErr = "Headers cannot be promoted without adjusting column names";
39
+ exports.unexpectedErr = "Unexpected error";
40
+ exports.arrayIsntMxNErr = "Array isn't MxN";
41
+ exports.blobFileType = "blob";
42
+ exports.uint8ArrayType = "uint8array";
43
+ exports.application = "application/xlsx";
44
+ exports.textResultType = "text";
45
+ exports.xmlTextResultType = "text/xml";
46
+ exports.pivotCachesPathPrefix = "pivotCacheDefinition";
47
+ exports.trueValue = "1";
48
+ exports.falseValue = "0";
49
+ exports.emptyValue = "";
50
+ exports.section1PathPrefix = "Section1/";
51
+ exports.divider = "/";
52
+ exports.maxQueryLength = 80;
53
+ exports.trueStr = "true";
54
+ exports.falseStr = "false";
55
+ exports.BOM = "\ufeff";
56
+ exports.element = {
57
+ sharedStringTable: "sst",
58
+ text: "t",
59
+ sharedStringItem: "si",
60
+ cellValue: "v",
61
+ databaseProperties: "dbPr",
62
+ queryTable: "queryTable",
63
+ cacheSource: "cacheSource",
64
+ item: "Item",
65
+ items: "Items",
66
+ itemPath: "ItemPath",
67
+ itemType: "ItemType",
68
+ itemLocation: "ItemLocation",
69
+ entry: "Entry",
70
+ stableEntries: "StableEntries",
71
+ tableColumns: "tableColumns",
72
+ tableColumn: "tableColumn",
73
+ table: "table",
74
+ autoFilter: "autoFilter",
75
+ definedName: "definedName",
76
+ queryTableFields: "queryTableFields",
77
+ queryTableField: "queryTableField",
78
+ queryTableRefresh: "queryTableRefresh",
79
+ sheetData: "sheetData",
80
+ row: "row",
81
+ dimension: "dimension",
82
+ kindCell: "c",
83
+ };
84
+ exports.elementAttributes = {
85
+ connection: "connection",
86
+ command: "command",
87
+ refreshOnLoad: "refreshOnLoad",
88
+ count: "count",
89
+ uniqueCount: "uniqueCount",
90
+ queryTable: "queryTable",
91
+ connectionId: "connectionId",
92
+ cacheSource: "cacheSource",
93
+ name: "name",
94
+ description: "description",
95
+ id: "id",
96
+ type: "Type",
97
+ value: "Value",
98
+ relationshipInfo: "RelationshipInfoContainer",
99
+ resultType: "ResultType",
100
+ fillColumnNames: "FillColumnNames",
101
+ fillTarget: "FillTarget",
102
+ fillLastUpdated: "FillLastUpdated",
103
+ day: "d",
104
+ uniqueName: "uniqueName",
105
+ queryTableFieldId: "queryTableFieldId",
106
+ reference: "ref",
107
+ tableColumnId: "tableColumnId",
108
+ nextId: "nextId",
109
+ row: "r",
110
+ spans: "spans",
111
+ x14acDyDescent: "x14ac:dyDescent",
112
+ xr3uid: "xr3:uid",
113
+ };
114
+ exports.dataTypeKind = {
115
+ string: "str",
116
+ number: "1",
117
+ boolean: "b",
118
+ };
119
+ exports.elementAttributesValues = {
120
+ connectionName: (queryName) => `Query - ${queryName}`,
121
+ connectionDescription: (queryName) => `Connection to the '${queryName}' query in the workbook.`,
122
+ connection: (queryName) => `Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location="${queryName}";`,
123
+ connectionCommand: (queryName) => `SELECT * FROM [${queryName}]`,
124
+ tableResultType: () => "sTable",
125
+ };
126
+ exports.defaults = {
127
+ queryName: "Query1",
128
+ sheetName: "Sheet1",
129
+ columnName: "Column",
130
+ };
131
+ exports.URLS = {
132
+ PQ: [
133
+ "http://schemas.microsoft.com/DataMashup",
134
+ "http://schemas.microsoft.com/DataExplorer",
135
+ "http://schemas.microsoft.com/DataMashup/Temp",
136
+ "http://schemas.microsoft.com/DataExplorer/Temp",
137
+ ],
138
+ CONNECTED_WORKBOOK: "http://schemas.microsoft.com/ConnectedWorkbook",
139
+ };
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
+ return new (P || (P = Promise))(function (resolve, reject) {
7
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11
+ });
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ const constants_1 = require("./constants");
15
+ const types_1 = require("../types");
16
+ const createOrUpdateProperty = (doc, parent, property, value) => {
17
+ if (value === undefined) {
18
+ return;
19
+ }
20
+ const elements = parent.getElementsByTagName(property);
21
+ if ((elements === null || elements === void 0 ? void 0 : elements.length) === 0) {
22
+ const newElement = doc.createElement(property);
23
+ newElement.textContent = value;
24
+ parent.appendChild(newElement);
25
+ }
26
+ else if (elements.length > 1) {
27
+ throw new Error(`Invalid DocProps core.xml, multiple ${property} elements`);
28
+ }
29
+ else if ((elements === null || elements === void 0 ? void 0 : elements.length) > 0) {
30
+ elements[0].textContent = value;
31
+ }
32
+ };
33
+ const getDocPropsProperties = (zip) => __awaiter(void 0, void 0, void 0, function* () {
34
+ var _a;
35
+ const docPropsCoreXmlString = yield ((_a = zip.file(constants_1.docPropsCoreXmlPath)) === null || _a === void 0 ? void 0 : _a.async(constants_1.textResultType));
36
+ if (docPropsCoreXmlString === undefined) {
37
+ throw new Error("DocProps core.xml was not found in template");
38
+ }
39
+ const parser = new DOMParser();
40
+ const doc = parser.parseFromString(docPropsCoreXmlString, constants_1.xmlTextResultType);
41
+ const properties = doc.getElementsByTagName(constants_1.docPropsRootElement).item(0);
42
+ if (properties === null) {
43
+ throw new Error("Invalid DocProps core.xml");
44
+ }
45
+ return { doc, properties };
46
+ });
47
+ const getCellReferenceAbsolute = (col, row) => {
48
+ // 65 is the ascii value of first column 'A'
49
+ return "$" + String.fromCharCode(col + 65) + "$" + row.toString();
50
+ };
51
+ const getCellReferenceRelative = (col, row) => {
52
+ // 65 is the ascii value of first column 'A'
53
+ return String.fromCharCode(col + 65) + row.toString();
54
+ };
55
+ const getTableReference = (numberOfCols, numberOfRows) => {
56
+ return `A1:${getCellReferenceRelative(numberOfCols, numberOfRows)}`;
57
+ };
58
+ const createCellElement = (doc, colIndex, rowIndex, data) => {
59
+ const cell = doc.createElementNS(doc.documentElement.namespaceURI, constants_1.element.kindCell);
60
+ cell.setAttribute(constants_1.elementAttributes.row, getCellReferenceRelative(colIndex, rowIndex + 1));
61
+ const cellData = doc.createElementNS(doc.documentElement.namespaceURI, constants_1.element.cellValue);
62
+ updateCellData(data, cell, cellData, rowIndex === 0);
63
+ cell.appendChild(cellData);
64
+ return cell;
65
+ };
66
+ const updateCellData = (data, cell, cellData, rowHeader) => {
67
+ switch (resolveType(data, rowHeader)) {
68
+ case types_1.DataTypes.string:
69
+ cell.setAttribute(constants_1.element.text, constants_1.dataTypeKind.string);
70
+ break;
71
+ case types_1.DataTypes.number:
72
+ cell.setAttribute(constants_1.element.text, constants_1.dataTypeKind.number);
73
+ break;
74
+ case types_1.DataTypes.boolean:
75
+ cell.setAttribute(constants_1.element.text, constants_1.dataTypeKind.boolean);
76
+ break;
77
+ }
78
+ cellData.textContent = data;
79
+ };
80
+ const resolveType = (originalData, rowHeader) => {
81
+ const data = originalData;
82
+ if (rowHeader) {
83
+ // Headers should be string by default.
84
+ return types_1.DataTypes.string;
85
+ }
86
+ let dataType = isNaN(Number(data)) ? types_1.DataTypes.string : types_1.DataTypes.number;
87
+ if (dataType == types_1.DataTypes.string) {
88
+ if (data.trim() == constants_1.trueStr || data.trim() == constants_1.falseStr) {
89
+ dataType = types_1.DataTypes.boolean;
90
+ }
91
+ }
92
+ return dataType;
93
+ };
94
+ exports.default = {
95
+ createOrUpdateProperty,
96
+ getDocPropsProperties,
97
+ getCellReferenceRelative,
98
+ getCellReferenceAbsolute,
99
+ createCell: createCellElement,
100
+ getTableReference,
101
+ resolveType,
102
+ };
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const constants_1 = require("../utils/constants");
6
+ const parseToTableData = (grid) => {
7
+ var _a, _b, _c, _d;
8
+ if (grid === null || grid === undefined) {
9
+ grid = { data: [] };
10
+ }
11
+ if (grid.data === null || grid.data === undefined) {
12
+ grid.data = [];
13
+ }
14
+ const mergedGrid = {
15
+ config: {
16
+ promoteHeaders: (_b = (_a = grid.config) === null || _a === void 0 ? void 0 : _a.promoteHeaders) !== null && _b !== void 0 ? _b : false,
17
+ adjustColumnNames: (_d = (_c = grid.config) === null || _c === void 0 ? void 0 : _c.adjustColumnNames) !== null && _d !== void 0 ? _d : true,
18
+ },
19
+ data: grid.data.map((row) => row.map((value) => { var _a; return (_a = value === null || value === void 0 ? void 0 : value.toString()) !== null && _a !== void 0 ? _a : ""; })),
20
+ };
21
+ correctGrid(mergedGrid);
22
+ validateGrid(mergedGrid);
23
+ let columnNames = [];
24
+ if (mergedGrid.config.promoteHeaders && mergedGrid.config.adjustColumnNames) {
25
+ columnNames = getAdjustedColumnNames(mergedGrid.data.shift());
26
+ }
27
+ else if (mergedGrid.config.promoteHeaders && !mergedGrid.config.adjustColumnNames) {
28
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
29
+ columnNames = mergedGrid.data.shift();
30
+ }
31
+ else {
32
+ columnNames = Array.from({ length: mergedGrid.data[0].length }, (_, index) => `${constants_1.defaults.columnName} ${index + 1}`);
33
+ }
34
+ return { columnNames: columnNames, rows: mergedGrid.data };
35
+ };
36
+ const correctGrid = (grid) => {
37
+ if (grid.data.length === 0) {
38
+ // empty grid fix
39
+ grid.config.promoteHeaders = false;
40
+ grid.data.push([""]);
41
+ return;
42
+ }
43
+ const getEmptyArray = (n) => Array.from({ length: n }, () => "");
44
+ if (grid.data[0].length === 0) {
45
+ grid.data[0] = [""];
46
+ }
47
+ // replace empty rows
48
+ grid.data.forEach((row, index) => {
49
+ if (row.length === 0) {
50
+ grid.data[index] = getEmptyArray(grid.data[0].length);
51
+ }
52
+ });
53
+ if (grid.config.promoteHeaders && grid.data.length === 1) {
54
+ // table in Excel should have at least 2 rows
55
+ grid.data.push(getEmptyArray(grid.data[0].length));
56
+ }
57
+ };
58
+ /*
59
+ * Validates the grid, throws an error if the grid is invalid.
60
+ * A valid grid has:
61
+ * - MxN structure.
62
+ * - If promoteHeaders is true - has at least 1 row, and in case adjustColumnNames is false, first row is unique and non empty.
63
+ */
64
+ const validateGrid = (grid) => {
65
+ validateDataArrayDimensions(grid.data);
66
+ if (grid.config.promoteHeaders && grid.config.adjustColumnNames === false && !validateUniqueAndValidDataArray(grid.data[0])) {
67
+ throw new Error(constants_1.promotedHeadersCannotBeUsedWithoutAdjustingColumnNamesErr);
68
+ }
69
+ };
70
+ const validateDataArrayDimensions = (arr) => {
71
+ if (arr.length === 0 || arr[0].length === 0) {
72
+ throw new Error(constants_1.unexpectedErr);
73
+ }
74
+ if (!arr.every((innerArr) => innerArr.length === arr[0].length)) {
75
+ throw new Error(constants_1.arrayIsntMxNErr);
76
+ }
77
+ };
78
+ const validateUniqueAndValidDataArray = (arr) => {
79
+ if (arr.some((element) => element === "")) {
80
+ return false; // Array contains empty elements
81
+ }
82
+ const uniqueSet = new Set(arr);
83
+ return uniqueSet.size === arr.length;
84
+ };
85
+ const getAdjustedColumnNames = (columnNames) => {
86
+ if (columnNames === undefined) {
87
+ throw new Error(constants_1.unexpectedErr);
88
+ }
89
+ let i = 1;
90
+ // replace empty column names with default names, can still conflict if columns exist, but we handle that later
91
+ columnNames = columnNames.map((columnName) => columnName || `${constants_1.defaults.columnName} ${i++}`);
92
+ const uniqueNames = new Set();
93
+ return columnNames.map((name) => {
94
+ let uniqueName = name;
95
+ i = 1;
96
+ while (uniqueNames.has(uniqueName)) {
97
+ uniqueName = `${name} (${i++})`;
98
+ }
99
+ uniqueNames.add(uniqueName);
100
+ return uniqueName;
101
+ });
102
+ };
103
+ exports.default = { parseToTableData };
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const extractTableValues = (table) => {
6
+ const rows = [];
7
+ // Extract values from each row
8
+ for (let i = 0; i < table.rows.length; i++) {
9
+ const row = table.rows[i];
10
+ const rowData = [];
11
+ for (let j = 0; j < row.cells.length; j++) {
12
+ const cell = row.cells[j];
13
+ rowData.push(cell.textContent || "");
14
+ }
15
+ rows.push(rowData);
16
+ }
17
+ return rows;
18
+ };
19
+ exports.default = { extractTableValues };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT license.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.gridUtils = exports.htmlUtils = exports.tableUtils = exports.xmlInnerPartsUtils = exports.xmlPartsUtils = exports.documentUtils = exports.arrayUtils = exports.pqUtils = void 0;
9
+ var pqUtils_1 = require("./pqUtils");
10
+ Object.defineProperty(exports, "pqUtils", { enumerable: true, get: function () { return __importDefault(pqUtils_1).default; } });
11
+ var arrayUtils_1 = require("./arrayUtils");
12
+ Object.defineProperty(exports, "arrayUtils", { enumerable: true, get: function () { return __importDefault(arrayUtils_1).default; } });
13
+ var documentUtils_1 = require("./documentUtils");
14
+ Object.defineProperty(exports, "documentUtils", { enumerable: true, get: function () { return __importDefault(documentUtils_1).default; } });
15
+ var xmlPartsUtils_1 = require("./xmlPartsUtils");
16
+ Object.defineProperty(exports, "xmlPartsUtils", { enumerable: true, get: function () { return __importDefault(xmlPartsUtils_1).default; } });
17
+ var xmlInnerPartsUtils_1 = require("./xmlInnerPartsUtils");
18
+ Object.defineProperty(exports, "xmlInnerPartsUtils", { enumerable: true, get: function () { return __importDefault(xmlInnerPartsUtils_1).default; } });
19
+ var tableUtils_1 = require("./tableUtils");
20
+ Object.defineProperty(exports, "tableUtils", { enumerable: true, get: function () { return __importDefault(tableUtils_1).default; } });
21
+ var htmlUtils_1 = require("./htmlUtils");
22
+ Object.defineProperty(exports, "htmlUtils", { enumerable: true, get: function () { return __importDefault(htmlUtils_1).default; } });
23
+ var gridUtils_1 = require("./gridUtils");
24
+ Object.defineProperty(exports, "gridUtils", { enumerable: true, get: function () { return __importDefault(gridUtils_1).default; } });