@ui5/webcomponents-tools 0.0.0-037d08c67

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 (124) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE.txt +201 -0
  3. package/README.md +21 -0
  4. package/assets-meta.js +154 -0
  5. package/bin/create-ui5-element.js +3 -0
  6. package/bin/dev.js +22 -0
  7. package/bin/ui5nps.js +301 -0
  8. package/components-package/eslint.js +195 -0
  9. package/components-package/nps.js +177 -0
  10. package/components-package/postcss.components.js +1 -0
  11. package/components-package/postcss.themes.js +1 -0
  12. package/components-package/vite.config.js +9 -0
  13. package/components-package/wdio.js +421 -0
  14. package/icons-collection/nps.js +80 -0
  15. package/lib/amd-to-es6/index.js +109 -0
  16. package/lib/amd-to-es6/no-remaining-require.js +33 -0
  17. package/lib/cem/cem.js +16 -0
  18. package/lib/cem/custom-elements-manifest.config.mjs +575 -0
  19. package/lib/cem/event.mjs +168 -0
  20. package/lib/cem/patch/@custom-elements-manifest/analyzer/cli.js +128 -0
  21. package/lib/cem/patch/@custom-elements-manifest/analyzer/package.json +59 -0
  22. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/browser-entrypoint.js +23 -0
  23. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/create.js +117 -0
  24. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/arrow-function.js +26 -0
  25. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/class-jsdoc.js +157 -0
  26. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/classes.js +20 -0
  27. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createArrowFunction.js +17 -0
  28. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createAttribute.js +24 -0
  29. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createClass.js +301 -0
  30. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createClassField.js +26 -0
  31. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createFunctionLike.js +73 -0
  32. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createMixin.js +33 -0
  33. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createVariable.js +22 -0
  34. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/handlers.js +338 -0
  35. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/custom-elements-define-calls.js +90 -0
  36. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/exports.js +156 -0
  37. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/function-like.js +24 -0
  38. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/mixins.js +29 -0
  39. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/reexported-wrapped-mixin-exports.js +84 -0
  40. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/variables.js +34 -0
  41. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/collect-phase/collect-imports.js +101 -0
  42. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst/catalyst.js +11 -0
  43. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst/controller.js +34 -0
  44. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst-major-2/catalyst.js +11 -0
  45. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst-major-2/controller.js +34 -0
  46. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/decorators/attr.js +53 -0
  47. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/decorators/custom-element-decorator.js +36 -0
  48. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/fast/fast.js +7 -0
  49. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/lit.js +13 -0
  50. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/member-denylist.js +21 -0
  51. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/method-denylist.js +20 -0
  52. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/property-decorator.js +94 -0
  53. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/static-properties.js +121 -0
  54. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/utils.js +66 -0
  55. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/stencil/stencil.js +129 -0
  56. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/index.js +80 -0
  57. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/link-phase/cleanup-classes.js +25 -0
  58. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/link-phase/field-denylist.js +22 -0
  59. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/link-phase/method-denylist.js +25 -0
  60. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/apply-inheritance.js +78 -0
  61. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/is-custom-element.js +34 -0
  62. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/link-class-to-tagname.js +27 -0
  63. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/remove-unexported-declarations.js +23 -0
  64. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/resolve-initializers.js +52 -0
  65. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/ast-helpers.js +186 -0
  66. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/cli-helpers.js +164 -0
  67. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/exports.js +44 -0
  68. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/find-external-manifests.js +67 -0
  69. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/imports.js +25 -0
  70. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/index.js +71 -0
  71. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/jsdoc.js +19 -0
  72. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/manifest-helpers.js +194 -0
  73. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/mixins.js +112 -0
  74. package/lib/cem/schema-internal.json +1422 -0
  75. package/lib/cem/schema.json +1098 -0
  76. package/lib/cem/types-internal.d.ts +808 -0
  77. package/lib/cem/types.d.ts +736 -0
  78. package/lib/cem/utils.mjs +429 -0
  79. package/lib/cem/validate.js +81 -0
  80. package/lib/chokidar/chokidar.js +28 -0
  81. package/lib/copy-and-watch/index.js +158 -0
  82. package/lib/copy-list/index.js +36 -0
  83. package/lib/create-icons/index.js +131 -0
  84. package/lib/create-illustrations/index.js +210 -0
  85. package/lib/create-new-component/Component.js +74 -0
  86. package/lib/create-new-component/ComponentTemplate.js +12 -0
  87. package/lib/create-new-component/index.js +115 -0
  88. package/lib/css-processors/css-processor-components.mjs +101 -0
  89. package/lib/css-processors/css-processor-themes.mjs +121 -0
  90. package/lib/css-processors/postcss-plugin.mjs +153 -0
  91. package/lib/css-processors/scope-variables.mjs +51 -0
  92. package/lib/css-processors/shared.mjs +47 -0
  93. package/lib/dev-server/custom-hot-update-plugin.js +39 -0
  94. package/lib/dev-server/dev-server.mjs +78 -0
  95. package/lib/dev-server/virtual-index-html-plugin.js +56 -0
  96. package/lib/eslint/eslint.js +44 -0
  97. package/lib/generate-js-imports/illustrations.js +87 -0
  98. package/lib/generate-json-imports/i18n.js +93 -0
  99. package/lib/generate-json-imports/themes.js +75 -0
  100. package/lib/hbs2lit/index.js +3 -0
  101. package/lib/hbs2lit/src/compiler.js +60 -0
  102. package/lib/hbs2lit/src/extendedAttributeMapping.js +12 -0
  103. package/lib/hbs2lit/src/includesReplacer.js +31 -0
  104. package/lib/hbs2lit/src/litVisitor2.js +278 -0
  105. package/lib/hbs2lit/src/partials2.js +51 -0
  106. package/lib/hbs2lit/src/partialsVisitor.js +187 -0
  107. package/lib/hbs2lit/src/svgProcessor.js +76 -0
  108. package/lib/hbs2ui5/RenderTemplates/LitRenderer.js +45 -0
  109. package/lib/hbs2ui5/index.js +119 -0
  110. package/lib/i18n/defaults.js +90 -0
  111. package/lib/i18n/toJSON.js +71 -0
  112. package/lib/icons-hash/icons-hash.mjs +149 -0
  113. package/lib/postcss-combine-duplicated-selectors/index.js +185 -0
  114. package/lib/remove-dev-mode/remove-dev-mode.mjs +51 -0
  115. package/lib/rimraf/rimraf.js +31 -0
  116. package/lib/scoping/get-all-tags.js +44 -0
  117. package/lib/scoping/lint-src.js +32 -0
  118. package/lib/scoping/missing-dependencies.js +65 -0
  119. package/lib/scoping/report-tags-usage.js +28 -0
  120. package/lib/scoping/scope-test-pages.js +41 -0
  121. package/lib/test-runner/test-runner.js +79 -0
  122. package/lib/vite-bundler/vite-bundler.mjs +35 -0
  123. package/package.json +86 -0
  124. package/tsconfig.json +18 -0
@@ -0,0 +1,187 @@
1
+ function Visitor() {
2
+ this.parents = [];
3
+ this.paths = [];
4
+ }
5
+
6
+ Visitor.prototype = {
7
+ constructor: Visitor,
8
+ mutating: true,
9
+
10
+ // Visits a given value. If mutating, will replace the value if necessary.
11
+ acceptKey: function(node, name) {
12
+ this.paths.push(name);
13
+ let value = this.accept(node[name]);
14
+ if (this.mutating) {
15
+ // Hacky sanity check: This may have a few false positives for type for the helper
16
+ // methods but will generally do the right thing without a lot of overhead.
17
+ if (value && !Visitor.prototype[value.type]) {
18
+ throw new Error("Unexpected node type \"" + value.type + "\" found when accepting " + name + " on " + node.type);
19
+ }
20
+ node[name] = value;
21
+ }
22
+ this.paths.pop();
23
+ },
24
+
25
+ // Performs an accept operation with added sanity check to ensure
26
+ // required keys are not removed.
27
+ acceptRequired: function(node, name) {
28
+ this.acceptKey(node, name);
29
+
30
+ if (!node[name]) {
31
+ throw new Error(node.type + " requires " + name);
32
+ }
33
+ },
34
+
35
+ // Traverses a given array. If mutating, empty respnses will be removed
36
+ // for child elements.
37
+ acceptArray: function(array) {
38
+ for (let i = 0, l = array.length; i < l; i++) {
39
+ this.acceptKey(array, i);
40
+
41
+ if (!array[i]) {
42
+ array.splice(i, 1);
43
+ i--;
44
+ l--;
45
+ }
46
+ }
47
+ },
48
+
49
+ accept: function(object) {
50
+ if (!object) {
51
+ return;
52
+ }
53
+
54
+ /* istanbul ignore next: Sanity code */
55
+ if (!this[object.type]) {
56
+ throw new Error("Unknown type: " + object.type, object);
57
+ }
58
+
59
+ if (this.current) {
60
+ this.parents.unshift(this.current);
61
+ }
62
+ this.current = object;
63
+
64
+ let ret = this[object.type](object);
65
+
66
+ this.current = this.parents.shift();
67
+
68
+ if (!this.mutating || ret) {
69
+ return ret;
70
+ } else if (ret !== false) {
71
+ return object;
72
+ }
73
+ },
74
+
75
+ Program: function(program) {
76
+ this.paths.push("body");
77
+ this.acceptArray(program.body);
78
+ this.paths.pop();
79
+ },
80
+
81
+ MustacheStatement: visitSubExpression,
82
+ Decorator: visitSubExpression,
83
+
84
+ BlockStatement: visitBlock,
85
+ DecoratorBlock: visitBlock,
86
+
87
+ PartialStatement: visitPartial,
88
+ PartialBlockStatement: function(partial) {
89
+ visitPartial.call(this, partial);
90
+
91
+ this.acceptKey(partial, "program");
92
+ },
93
+
94
+ ContentStatement: function(/* content */) {},
95
+ CommentStatement: function(/* comment */) {},
96
+
97
+ SubExpression: visitSubExpression,
98
+
99
+ PathExpression: function(/* path */) {},
100
+
101
+ StringLiteral: function(/* string */) {},
102
+ NumberLiteral: function(/* number */) {},
103
+ BooleanLiteral: function(/* bool */) {},
104
+ UndefinedLiteral: function(/* literal */) {},
105
+ NullLiteral: function(/* literal */) {},
106
+
107
+ Hash: function(hash) {
108
+ this.paths.push("pairs");
109
+ this.acceptArray(hash.pairs);
110
+ this.paths.pop();
111
+ },
112
+ HashPair: function(pair) {
113
+ this.acceptRequired(pair, "value");
114
+ }
115
+ };
116
+
117
+ function visitSubExpression(mustache) {
118
+ this.acceptRequired(mustache, "path");
119
+ this.paths.push("params");
120
+ this.acceptArray(mustache.params);
121
+ this.paths.pop();
122
+ this.acceptKey(mustache, "hash");
123
+ }
124
+ function visitBlock(block) {
125
+ visitSubExpression.call(this, block);
126
+
127
+ this.acceptKey(block, "program");
128
+ this.acceptKey(block, "inverse");
129
+ }
130
+ function visitPartial(partial) {
131
+ this.acceptRequired(partial, "name");
132
+ this.paths.push("params");
133
+ this.acceptArray(partial.params);
134
+ this.paths.pop();
135
+ this.acceptKey(partial, "hash");
136
+ }
137
+
138
+ ////////////
139
+
140
+ function PartialsVisitor() {
141
+ this.partialDefinitions = {};
142
+ this.partials = [];
143
+ }
144
+
145
+ PartialsVisitor.prototype = new Visitor();
146
+
147
+ PartialsVisitor.prototype.PartialStatement = function(node) {
148
+ this.partials.push({
149
+ nodes: this.paths.slice(0),
150
+ name: node.name.original
151
+ });
152
+ Visitor.prototype.PartialStatement.call(this, node);
153
+ };
154
+
155
+ PartialsVisitor.prototype.DecoratorBlock = function(node) {
156
+ if (node.path.original === "ui5.inline" || node.path.original === "inline") {
157
+ let name = node.params[0].original;
158
+ this.partialDefinitions[name] = Object.assign({}, node);
159
+ }
160
+
161
+ Visitor.prototype.DecoratorBlock.call(this, node);
162
+
163
+ return false;
164
+ };
165
+
166
+ PartialsVisitor.prototype.collect = function(node) {
167
+ return Visitor.prototype.accept(node);
168
+ };
169
+
170
+ PartialsVisitor.prototype.modify = function(node) {
171
+ for (let i = this.partials.length - 1; i >= 0; i--) {
172
+ let partial = this.partials[i];
173
+ let parentNode = node;
174
+
175
+ //find the parent node - it's always inside the body of some Program node
176
+ while (partial.nodes.length > 1) {
177
+ parentNode = parentNode[partial.nodes.shift()];
178
+ }
179
+
180
+ let nodeName = partial.nodes.shift();
181
+ if (Array.isArray(parentNode) && typeof (nodeName) === "number") {
182
+ parentNode.splice(nodeName, 1, ...this.partialDefinitions[partial.name].program.body);
183
+ }
184
+ }
185
+ };
186
+
187
+ module.exports = PartialsVisitor;
@@ -0,0 +1,76 @@
1
+
2
+ const svgrx = new RegExp(/<svg[\s\S]*?>([\s\S]*?)<\/svg>/, 'g');
3
+ const blockrx = /block[0-9]+/g;
4
+
5
+ function processSVG(input) {
6
+ let matches;
7
+ let template = input;
8
+ let blockCounter = 0;
9
+
10
+ matches = getSVGMatches(template);
11
+
12
+ if (!matches.length) {
13
+ return template;
14
+ }
15
+
16
+ matches.forEach(match => {
17
+ //(1) extract the SVG content as a separate block
18
+ const svgContentGroup = match[1];
19
+ const block = getSVGBlock(svgContentGroup, ++blockCounter);
20
+
21
+ // (2) replace the SVG content with its block called, e.g ${blockSVG(context)}
22
+ template = template.replace(svgContentGroup, block.usage);
23
+
24
+ // (3) look for internal blocks in the SVG content and replace their `html with `svg
25
+ template = replaceInternalBlocks(template, svgContentGroup);
26
+
27
+ // (4) append the SVG block definiton (built in step 1), e.g const blockSVG = (context) => {return svg`.*`}
28
+ template += block.definition;
29
+ });
30
+
31
+ return template;
32
+ }
33
+
34
+ function getSVGMatches(template) {
35
+ let matches = [];
36
+
37
+ while (svgMatch = svgrx.exec(template)) {
38
+ matches.push(svgMatch);
39
+ if (svgrx.lastIndex === svgMatch.index) {
40
+ svgrx.lastIndex++;
41
+ }
42
+ }
43
+
44
+ return matches;
45
+ }
46
+
47
+ function getSVGBlock(input, blockCounter) {
48
+ const definitionTS = `\nfunction blockSVG${blockCounter} (this: any, context: UI5Element, tags: string[], suffix: string | undefined) {
49
+ return svg\`${input}\`;
50
+ };`;
51
+ const definitionJS = `\nfunction blockSVG${blockCounter} (context, tags, suffix) {
52
+ return svg\`${input}\`;
53
+ };`;
54
+
55
+ return {
56
+ usage: `\${blockSVG${blockCounter}.call(this, context, tags, suffix)}`,
57
+ definition: process.env.UI5_TS ? definitionTS : definitionJS,
58
+ };
59
+ }
60
+
61
+ function replaceInternalBlocks(template, svgContent) {
62
+ const internalBlocks = svgContent.match(blockrx) || [];
63
+
64
+ internalBlocks.forEach(blockName => {
65
+ const rx = new RegExp(`function ${blockName}.*(html\`).*;`);
66
+ template = template.replace(rx, (match, p1) => {
67
+ return match.replace(p1, "svg\`");
68
+ });
69
+ });
70
+
71
+ return template;
72
+ }
73
+
74
+ module.exports = {
75
+ process: processSVG,
76
+ };
@@ -0,0 +1,45 @@
1
+ const tsImports = (controlName, hasTypes) => {
2
+ if (!process.env.UI5_TS) {
3
+ return "";
4
+ }
5
+
6
+ const importPrefix = process.env.UI5_BASE ? "../../../../../src/" : "@ui5/webcomponents-base/dist/"
7
+
8
+ return `import type UI5Element from "${importPrefix}UI5Element.js";
9
+ ${importForControl(controlName, hasTypes)}
10
+ import type { ClassMapValue } from "${importPrefix}types.js";
11
+ `;
12
+ }
13
+ const importForControl = (controlName, hasTypes) => {
14
+
15
+ if (!hasTypes) {
16
+ return `type ${controlName} = any;`;
17
+ }
18
+
19
+ if (process.env.UI5_BASE) {
20
+ // base package has a component in `test/elements` instead of `src`
21
+ return `import type ${controlName} from "../../../${controlName}.js";`
22
+ }
23
+ return `import type ${controlName} from "../../${controlName}.js";`
24
+ }
25
+
26
+ const buildRenderer = (controlName, litTemplate, hasTypes) => {
27
+ const importPrefix = process.env.UI5_BASE ? "../../../../../src/" : "@ui5/webcomponents-base/dist/";
28
+
29
+ const mainTemplateFunction = process.env.UI5_TS ?
30
+ `function template(this: ${controlName}) { return block0.call(this, this, (this.constructor as typeof UI5Element).tagsToScope, getCustomElementsScopingSuffix()); }` :
31
+ `function template() { return block0.call(this, this, this.constructor.tagsToScope, getCustomElementsScopingSuffix()); }`;
32
+
33
+ // typescript cannot process package imports for the same package and the paths are changed to relative for base package templates
34
+ return `/* eslint no-unused-vars: 0 */
35
+ import { html, svg, repeat, classMap, styleMap, ifDefined, unsafeHTML, scopeTag } from "${importPrefix}renderer/LitRenderer.js";
36
+ import { getCustomElementsScopingSuffix } from "${importPrefix}CustomElementsScopeUtils.js";
37
+ ${tsImports(controlName, hasTypes)}
38
+ ${litTemplate}
39
+ ${mainTemplateFunction}
40
+ export default template;`;
41
+ };
42
+
43
+ module.exports = {
44
+ generateTemplate: buildRenderer
45
+ };
@@ -0,0 +1,119 @@
1
+ const fs = require('fs').promises;
2
+ const existsSync = require('fs').existsSync;
3
+ const getopts = require('getopts');
4
+ const hbs2lit = require('../hbs2lit');
5
+ const path = require('path');
6
+ const litRenderer = require('./RenderTemplates/LitRenderer');
7
+ const recursiveReadDir = require("recursive-readdir");
8
+
9
+ let missingTypesReported = false;
10
+
11
+ const args = getopts(process.argv.slice(2), {
12
+ alias: {
13
+ o: 'output',
14
+ d: 'directory',
15
+ f: 'file',
16
+ t: 'type'
17
+ },
18
+ default: {
19
+ t: 'lit-html'
20
+ }
21
+ });
22
+
23
+ const onError = (place) => {
24
+ console.log(`A problem occoured when reading ${place}. Please recheck passed parameters.`);
25
+ };
26
+
27
+ const isHandlebars = (fileName) => fileName.endsWith('.hbs');
28
+
29
+ const hasTypes = (file, componentName) => {
30
+ const tsFile = path.join(path.dirname(file), componentName + ".ts")
31
+ const dtsFile = path.join(path.dirname(file), componentName + ".d.ts")
32
+ return existsSync(tsFile) || existsSync(dtsFile);
33
+ }
34
+
35
+ const processFile = async (file, outputDir) => {
36
+ const componentNameMatcher = /(\w+)(\.hbs)/gim;
37
+ const componentName = componentNameMatcher.exec(file)[1];
38
+ const componentHasTypes = hasTypes(file, componentName);
39
+ if (!componentHasTypes) {
40
+ if (!missingTypesReported) {
41
+ console.warn("[Warn] The following templates do not have a corresponging .ts or .d.ts file and won't be type checked:")
42
+ missingTypesReported = true;
43
+ }
44
+ console.log(" -> " + componentName + ".hbs");
45
+ }
46
+ const litCode = await hbs2lit(file, componentName);
47
+ const absoluteOutputDir = composeAbsoluteOutputDir(file, outputDir);
48
+
49
+ return writeRenderers(absoluteOutputDir, componentName, litRenderer.generateTemplate(componentName, litCode, componentHasTypes));
50
+ };
51
+
52
+ const composeAbsoluteOutputDir = (file, outputDir) => {
53
+ // (1) Extract the dir structure from the source file path - "src/lvl1/lvl2/MyCompBadge.hbs"
54
+ // - remove the filename - "src/lvl1/lvl2"
55
+ // - remove the leading dir - "lvl1/lvl2"
56
+ const fileDir = file.split(path.sep).slice(1, -1).join(path.sep);
57
+
58
+ // (2) Compose full output dir - "dist/generated/templates/lvl1/lvl2"
59
+ return `${outputDir}${path.sep}${fileDir}`;
60
+ };
61
+
62
+ const wrapDirectory = (directory, outputDir) => {
63
+ directory = path.normalize(directory);
64
+ outputDir = path.normalize(outputDir);
65
+
66
+ return new Promise((resolve, reject) => {
67
+ recursiveReadDir(directory, (err, files) => {
68
+
69
+ if (err) {
70
+ onError('directory');
71
+ reject();
72
+ }
73
+
74
+ const promises = files.map(fileName => {
75
+ if (isHandlebars(fileName)) {
76
+ return processFile(fileName, outputDir);
77
+ }
78
+ }).filter(x => !!x);
79
+
80
+ resolve(Promise.all(promises));
81
+ });
82
+ });
83
+ };
84
+
85
+ const writeRenderers = async (outputDir, controlName, fileContent) => {
86
+ try {
87
+
88
+ await fs.mkdir(outputDir, { recursive: true });
89
+
90
+ const compiledFilePath = `${outputDir}${path.sep}${controlName}Template.lit.${process.env.UI5_TS ? "ts" : "js"}`;
91
+
92
+ // strip DOS line endings because the break the source maps
93
+ let fileContentUnix = fileContent.replace(/\r\n/g, "\n");
94
+ fileContentUnix = fileContentUnix.replace(/\r/g, "\n");
95
+
96
+ // Only write to the file system actual changes - each updated file, no matter if the same or not, triggers an expensive operation for rollup
97
+ // Note: .hbs files that include a changed .hbs file will also be recompiled as their content will be updated too
98
+
99
+ let existingFileContent = "";
100
+ try {
101
+ existingFileContent = (await fs.readFile(compiledFilePath)).toString();
102
+ } catch (e) {}
103
+
104
+ if (existingFileContent !== fileContentUnix) {
105
+ return fs.writeFile(compiledFilePath, fileContentUnix);
106
+ }
107
+
108
+ } catch (e) {
109
+ console.log(e);
110
+ }
111
+ };
112
+
113
+ if (!args['d'] || !args['o']) {
114
+ console.log('Please provide an input and output directory (-d and -o)');
115
+ } else {
116
+ wrapDirectory(args['d'], args['o']).then(() => {
117
+ console.log("Templates generated");
118
+ });
119
+ }
@@ -0,0 +1,90 @@
1
+ const fs = require('fs').promises;
2
+ const path = require('path');
3
+ const PropertiesReader = require('properties-reader');
4
+ const assets = require('../../assets-meta.js');
5
+
6
+ const generate = async (argv) => {
7
+ const defaultLanguage = assets.languages.default;
8
+
9
+ const messageBundle = path.normalize(`${argv[2]}/messagebundle.properties`);
10
+ const messageBundleDefaultLanguage = path.normalize(`${argv[2]}/messagebundle_${defaultLanguage}.properties`);
11
+ const tsMode = process.env.UI5_TS === "true"; // In Typescript mode, we output .ts files and set the required types, otherwise - output pure .js files
12
+
13
+ const outputFile = path.normalize(`${argv[3]}/i18n-defaults.${tsMode ? "ts" : "js"}`);
14
+
15
+ if (!messageBundle || !outputFile) {
16
+ return;
17
+ }
18
+
19
+ const properties = PropertiesReader(messageBundle)._properties;
20
+
21
+ let defaultLanguageProperties;
22
+ try {
23
+ defaultLanguageProperties = PropertiesReader(messageBundleDefaultLanguage)._properties;
24
+ } catch (e) {
25
+ }
26
+
27
+ // Merge messagebundle.properties and messagebundle_en.properties files to generate the default texts.
28
+ // Note:
29
+ // (1) at DEV time, it's intuituve to work with the source bundle file - the messagebundle.properties,
30
+ // and see the changes there take effect.
31
+ // (2) as the messagebundle.properties file is always written in English,
32
+ // it makes sense to consider the messagebundle.properties content only when the default language is "en".
33
+ if (defaultLanguage === "en") {
34
+ // use messagebundle_en.properties to overwrite all developer properties, only the not translated ones will remain
35
+ defaultLanguageProperties = Object.assign({}, properties, defaultLanguageProperties);
36
+ }
37
+
38
+ /*
39
+ * Returns the single text object to enable single export.
40
+ *
41
+ * Example:
42
+ * const ARIA_LABEL_CARD_CONTENT = {
43
+ * key: "ARIA_LABEL_CARD_CONTENT",
44
+ * defaultText: "Card Content",
45
+ * };
46
+ */
47
+ const getTextInfo = (key, value, defaultLanguageValue) => {
48
+ let effectiveValue = defaultLanguageValue || value;
49
+ effectiveValue = effectiveValue.replace(/\"/g, "\\\""); // escape double quotes in translations
50
+
51
+ if (tsMode) {
52
+ return `const ${key}: I18nText = {key: "${key}", defaultText: "${effectiveValue}"};`;
53
+ }
54
+ return `const ${key} = {key: "${key}", defaultText: "${effectiveValue}"};`;
55
+ };
56
+
57
+ /*
58
+ * Returns the complete content of i18n-defaults.js file:
59
+ * (1) the single text objects
60
+ * (2) the export statement at the end of the file
61
+ *
62
+ * Example:
63
+ * export {
64
+ * ARIA_LABEL_CARD_CONTENT,
65
+ * }
66
+ */
67
+ const getOutputFileContent = (properties, defaultLanguageProperties) => {
68
+ const textKeys = Object.keys(properties);
69
+ const texts = textKeys.map(prop => getTextInfo(prop, properties[prop], defaultLanguageProperties && defaultLanguageProperties[prop])).join('');
70
+
71
+ // tabs are intentionally mixed to have proper identation in the produced file
72
+ return `${tsMode ? `import type { I18nText } from "@ui5/webcomponents-base/dist/i18nBundle.js";` : ""}
73
+ ${texts}
74
+ export {${textKeys.join()}};`;
75
+ };
76
+
77
+ await fs.mkdir(path.dirname(outputFile), { recursive: true });
78
+ await fs.writeFile(outputFile, getOutputFileContent(properties, defaultLanguageProperties));
79
+
80
+
81
+ if (process.env.UI5_VERBOSE === "true") {
82
+ console.log("i18n default file generated.");
83
+ }
84
+ };
85
+
86
+ if (require.main === module) {
87
+ generate(process.argv)
88
+ }
89
+
90
+ exports._ui5mainFn = generate;
@@ -0,0 +1,71 @@
1
+ /*
2
+ * The script converts all messebindle_*.properties files to messagebundle_*.json files.
3
+ *
4
+ * Execution (note: the paths depends on the the execution context)
5
+ * node toJSON.js ../../src/assets/i18n ../../dist/generated/assets/i18n
6
+ *
7
+ * The 1st param '../../src/assets/i18n' is the location of messagebundle_*.properties files
8
+ * The 2nd param './../dist/generated/assets/i18n' is where the JSON files would be written to.
9
+ */
10
+ const path = require("path");
11
+ const PropertiesReader = require('properties-reader');
12
+ const fs = require('fs').promises;
13
+ const assets = require('../../assets-meta.js');
14
+
15
+ const allLanguages = assets.languages.all;
16
+
17
+ /**
18
+ * The translation system has a configuration whether to return UTF-8 sequences
19
+ * or the actual characters. This function inlines UTF-8 sequences to actual characters.
20
+ *
21
+ * For example, it converts "Keine Produkte erf\u00FCgbar" to "Keine Produkte verfügbar"
22
+ * This makes the JSON files more readable and smaller.
23
+ */
24
+ function inlineUTF(properties) {
25
+ for (const key in properties) {
26
+ if (Object.prototype.hasOwnProperty.call(properties, key)) {
27
+ try {
28
+ // escape double quotes to avoid JSON parse error
29
+ const escaped = properties[key].replaceAll("\"", "\\\"");
30
+ properties[key] = JSON.parse(`"${escaped}"`); // utilize JSON parser to decode UTF-8 sequences
31
+ } catch (e) {
32
+ // in case of error, just keep the original string
33
+ console.log(`Warning: failed to inline UTF-8 for key "${key}" with value "${properties[key]}"`);
34
+ }
35
+ }
36
+ }
37
+ return properties;
38
+ }
39
+
40
+ const convertToJSON = async (file, distPath) => {
41
+ const properties = inlineUTF(PropertiesReader(file)._properties);
42
+ const filename = path.basename(file, path.extname(file));
43
+ const language = filename.match(/^messagebundle_(.*?)$/)[1];
44
+ if (!allLanguages.includes(language)) {
45
+ console.warn("Not supported language or script: ", language);
46
+ }
47
+ const outputFile = path.normalize(`${distPath}/${filename}.json`);
48
+
49
+ return fs.writeFile(outputFile, JSON.stringify(properties));
50
+ // console.log(`[i18n]: "${filename}.json" has been generated!`);
51
+ };
52
+
53
+ const generate = async (agrv) => {
54
+ const { globby } = await import("globby");
55
+ const messagesBundles = path.normalize(`${agrv[2]}/messagebundle_*.properties`);
56
+ const messagesJSONDist = path.normalize(`${agrv[3]}`);
57
+ await fs.mkdir(messagesJSONDist, { recursive: true });
58
+ const files = await globby(messagesBundles.replace(/\\/g, "/"));
59
+ return Promise.all(files.map(file => convertToJSON(file, messagesJSONDist)))
60
+ .then(() => {
61
+ if (process.env.UI5_VERBOSE === "true") {
62
+ console.log("Message bundle JSON files generated.");
63
+ }
64
+ });
65
+ };
66
+
67
+ if (require.main === module) {
68
+ generate(process.argv)
69
+ }
70
+
71
+ exports._ui5mainFn = generate;