diff --git a/dist/js/class/DirectoryCleaner.js b/dist/js/class/DirectoryCleaner.js new file mode 100644 index 0000000..840a91f --- /dev/null +++ b/dist/js/class/DirectoryCleaner.js @@ -0,0 +1,62 @@ +"use strict"; +// class/DirectoryCleaner.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fs_1 = require("fs"); +const path_1 = require("path"); +// ============================================================================ +// Classes +// ============================================================================ +class DirectoryCleaner { + /** + * Recursively deletes all contents of the directory asynchronously. + * @param dirPath The path to the directory to clean. + */ + cleanDirectory(dirPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const files = yield fs_1.promises.readdir(dirPath); + for (const file of files) { + const curPath = path_1.default.join(dirPath, file); + const stat = yield fs_1.promises.lstat(curPath); + if (stat.isDirectory()) { + yield this.cleanDirectory(curPath); + } + else { + yield fs_1.promises.unlink(curPath); + } + } + yield fs_1.promises.rmdir(dirPath); + } + catch (error) { + console.error(`Error cleaning directory ${dirPath}: ${error}`); + throw error; // Rethrow the error for further handling if necessary + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = DirectoryCleaner; diff --git a/dist/js/class/DirectoryCopier.js b/dist/js/class/DirectoryCopier.js new file mode 100644 index 0000000..947b2a6 --- /dev/null +++ b/dist/js/class/DirectoryCopier.js @@ -0,0 +1,64 @@ +"use strict"; +// class/DirectoryCopier.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path_1 = require("path"); +const fs_1 = require("fs"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for copying files from one directory to another. + */ +class DirectoryCopier { + /** + * Copies all files and subdirectories from a source directory to a destination directory. + * @param srcDir The source directory path. + * @param destDir The destination directory path. + * @throws Will throw an error if copying fails for any file or directory. + */ + copyFiles(srcDir, destDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const resolvedSrcDir = path_1.default.resolve(srcDir); + const resolvedDestDir = path_1.default.resolve(destDir); + yield this.recursiveCopy(resolvedSrcDir, resolvedDestDir); + console.log(`Files copied from ${resolvedSrcDir} to ${resolvedDestDir}`); + } + catch (error) { + console.error('Error copying files:', error); + throw error; + } + }); + } + /** + * Recursively copies files and directories. + * @param srcDir Source directory. + * @param destDir Destination directory. + */ + recursiveCopy(srcDir, destDir) { + return __awaiter(this, void 0, void 0, function* () { + yield fs_1.promises.mkdir(destDir, { recursive: true }); + const entries = yield fs_1.promises.readdir(srcDir, { withFileTypes: true }); + for (let entry of entries) { + const srcPath = path_1.default.join(srcDir, entry.name); + const destPath = path_1.default.join(destDir, entry.name); + entry.isDirectory() ? + yield this.recursiveCopy(srcPath, destPath) : + yield fs_1.promises.copyFile(srcPath, destPath); + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = DirectoryCopier; diff --git a/dist/js/class/DirectoryCreator.js b/dist/js/class/DirectoryCreator.js new file mode 100644 index 0000000..42b0793 --- /dev/null +++ b/dist/js/class/DirectoryCreator.js @@ -0,0 +1,65 @@ +"use strict"; +// class/DirectoryGenerator.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fs_1 = require("fs"); +const path_1 = require("path"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for creating directories. + */ +class DirectoryCreator { + /** + * Creates directories at the specified locations asynchronously. + * @param basePath The base path where directories will be created. + * @param directories An array of directory paths to create. + * @description This method iterates over the provided array of directory paths, + * creating each directory at the specified location within the base path. + * If a directory already exists, it skips creation. This is useful for + * setting up a project structure or ensuring necessary directories are + * available before performing file operations. + * @throws Will throw an error if directory creation fails. + */ + createDirectories(basePath, directories) { + return __awaiter(this, void 0, void 0, function* () { + try { + for (const dir of directories) { + const dirPath = path_1.default.join(basePath, dir); + yield fs_1.promises.mkdir(dirPath, { recursive: true }); + console.log(`Directory created or already exists: ${dirPath}`); + } + } + catch (error) { + console.error(`Error creating directories: ${error}`); + throw error; + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = DirectoryCreator; diff --git a/dist/js/class/FileCopier.js b/dist/js/class/FileCopier.js new file mode 100644 index 0000000..68d0064 --- /dev/null +++ b/dist/js/class/FileCopier.js @@ -0,0 +1,59 @@ +"use strict"; +// class/FileCopier.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fs_1 = require("fs"); +const path_1 = require("path"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for copying files from one location to another. + */ +class FileCopier { + /** + * Copies a single file to a specified destination directory. + * @param {string} srcFile - The path of the source file to copy. + * @param {string} destDir - The destination directory where the file should be copied. + * @throws Will throw an error if the file copy operation fails. + */ + copyFileToDirectory(srcFile, destDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const fileName = path_1.default.basename(srcFile); + const destFilePath = path_1.default.join(destDir, fileName); + yield fs_1.default.promises.copyFile(srcFile, destFilePath); + console.log(`File copied from ${srcFile} to ${destFilePath}`); + } + catch (error) { + console.error('Error copying file:', error); + throw error; + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = FileCopier; diff --git a/dist/js/class/FileRenamer.js b/dist/js/class/FileRenamer.js new file mode 100644 index 0000000..75f4f61 --- /dev/null +++ b/dist/js/class/FileRenamer.js @@ -0,0 +1,56 @@ +"use strict"; +// class/FileRenamer.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fs_1 = require("fs"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for renaming files. + */ +class FileRenamer { + /** + * Renames a file from the source path to the target path. + * @param srcPath The current path of the file. + * @param targetPath The new path of the file after renaming. + * @returns Promise + */ + renameFile(srcPath, targetPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield fs_1.default.promises.rename(srcPath, targetPath); + console.log(`File renamed from ${srcPath} to ${targetPath}`); + } + catch (error) { + console.error('Error renaming file:', error); + throw error; + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = FileRenamer; diff --git a/dist/js/class/FontGenerator.js b/dist/js/class/FontGenerator.js new file mode 100644 index 0000000..ea32783 --- /dev/null +++ b/dist/js/class/FontGenerator.js @@ -0,0 +1,123 @@ +"use strict"; +// class/FontGenerator.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fantasticon_1 = require("fantasticon"); +// ============================================================================ +// Classes +// ============================================================================ +class FontGenerator { + generateFonts(sourceDirectory, outputDiectory) { + return __awaiter(this, void 0, void 0, function* () { + const config = { + // RunnerMandatoryOptions + inputDir: sourceDirectory, // (required) + outputDir: outputDiectory, // (required) + // RunnerOptionalOptions + name: 'icon.gl', + fontTypes: [ + fantasticon_1.FontAssetType.TTF, // TTF = "ttf" + fantasticon_1.FontAssetType.WOFF, // WOFF = "woff" + fantasticon_1.FontAssetType.WOFF2, // WOFF2 = "woff2" + fantasticon_1.FontAssetType.EOT, // EOT = "eot" + fantasticon_1.FontAssetType.SVG, // SVG = "svg" + ], + assetTypes: [ + fantasticon_1.OtherAssetType.CSS, // CSS = "css", + fantasticon_1.OtherAssetType.SCSS, // SCSS = "scss", + fantasticon_1.OtherAssetType.SASS, // SASS = "sass", + fantasticon_1.OtherAssetType.HTML, // HTML = "html", + fantasticon_1.OtherAssetType.JSON, // JSON = "json", + fantasticon_1.OtherAssetType.TS, // TS = "ts" + ], + formatOptions: { + // woff: { + // // Woff Extended Metadata Block - see https://www.w3.org/TR/WOFF/#Metadata + // metadata: '...' + // }, + // ttf?: TtfOptions; // type TtfOptions = svg2ttf.FontOptions; + // svg?: SvgOptions; // type SvgOptions = Omit; + json: { indent: 4 }, + // ts: { + // // select what kind of types you want to generate + // // (default `['enum', 'constant', 'literalId', 'literalKey']`) + // types: ['enum', 'constant', 'literalId', 'literalKey'], + // // render the types with `'` instead of `"` (default is `"`) + // singleQuotes: false, + // // customise names used for the generated types and constants + // enumName: 'icon_gl', + // constantName: 'MY_CODEPOINTS' + // // literalIdName: 'IconId', + // // literalKeyName: 'IconKey' + // } + }, + pathOptions: { + json: './dist/font/icon.gl.json', + css: './dist/font/icon.gl.css', + scss: './dist/font/icon.gl.scss', + woff: './dist/font/icon.gl.woff', + woff2: './dist/font/icon.gl.woff2', + }, + // codepoints: { + // 'chevron-left': 57344, // decimal representation of 0xe000 + // 'chevron-right': 57345, + // 'thumbs-up': 57358, + // 'thumbs-down': 57359, + // }, + // fontHeight: number; + // descent: number; + // normalize: boolean; + // round: number; + selector: '.igl', + // tag: string; + // Use our custom Handlebars templates + // templates: { + // css: './build/font/icon.gl.css.hbs', + // scss: './build/font/icon.gl.scss.hbs' + // }, + prefix: 'igl', + fontsUrl: './fonts', + // Customize generated icon IDs (unavailable with `.json` config file) + // getIconId: ({ + // basename, // `string` - Example: 'foo'; + // relativeDirPath, // `string` - Example: 'sub/dir/foo.svg' + // absoluteFilePath, // `string` - Example: '/var/icons/sub/dir/foo.svg' + // relativeFilePath, // `string` - Example: 'foo.svg' + // index // `number` - Example: `0` + // }) => [index, basename].join('_') // '0_foo' + }; + try { + yield (0, fantasticon_1.generateFonts)(config); + console.log('Fonts generated successfully.'); + } + catch (error) { + console.error('Error generating fonts:', error); + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = FontGenerator; diff --git a/dist/js/class/JavaScriptMinifier.js b/dist/js/class/JavaScriptMinifier.js new file mode 100644 index 0000000..142a5dd --- /dev/null +++ b/dist/js/class/JavaScriptMinifier.js @@ -0,0 +1,74 @@ +"use strict"; +// class/JavaScriptMinifier.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const terser_1 = require("terser"); +const fs_1 = require("fs"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * Class to minify JavaScript files using Terser. + */ +class JavaScriptMinifier { + /** + * Constructs an instance with the provided configuration. + * @param {any} config - Configuration object - minification options for Terser. + */ + constructor(config) { + this.config = config; + } + /** + * Minifies a JavaScript file. + * @param {string} inputPath - Path to the input JavaScript file. + * @param {string} outputPath - Path to save the minified output file. + * @returns {Promise} - A promise that resolves when minification is complete. + */ + minifyFile(inputPath, outputPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + // Read the input file + const inputCode = yield fs_1.promises.readFile(inputPath, 'utf8'); + // Minify the file using Terser + // const result = await minify(inputCode, options); + const result = yield (0, terser_1.minify)(inputCode, this.config); + // If minification is successful, write the output + if (result.code) { + yield fs_1.promises.writeFile(outputPath, result.code); + } + else { + throw new Error('Minification resulted in empty output.'); + } + } + catch (error) { + console.error(`Error minifying JavaScript file ${inputPath}:`, error); + throw error; + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = JavaScriptMinifier; diff --git a/dist/js/class/PackageCreator.js b/dist/js/class/PackageCreator.js new file mode 100644 index 0000000..13869fc --- /dev/null +++ b/dist/js/class/PackageCreator.js @@ -0,0 +1,59 @@ +"use strict"; +// class/PackageCreator.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fs_1 = require("fs"); +const path_1 = require("path"); +// import * as pack from '../../package.json' assert { type: 'json' }; +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for creating a package.json file for a project. + */ +class PackageCreator { + /** + * Initializes a new instance of the PackageCreator class. + * @param {PackageJson} packageJson - The content to be written into package.json. + */ + constructor(packageJson) { + this.packageJson = packageJson; + } + /** + * Creates a package.json file in the specified directory. + * @param {string} outputDir - The directory where package.json will be created. + */ + createPackageJson(outputDir) { + return __awaiter(this, void 0, void 0, function* () { + const filePath = path_1.default.join(outputDir, 'package.json'); + const data = JSON.stringify(this.packageJson, null, 2); + fs_1.default.writeFileSync(filePath, data, 'utf-8'); + console.log(`package.json created at ${filePath}`); + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = PackageCreator; diff --git a/dist/js/class/StyleProcessor.js b/dist/js/class/StyleProcessor.js new file mode 100644 index 0000000..5094be7 --- /dev/null +++ b/dist/js/class/StyleProcessor.js @@ -0,0 +1,81 @@ +"use strict"; +// class/StyleProcessor.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const sass = require("sass"); +const postcss_1 = require("postcss"); +const fs_1 = require("fs"); +const postcss_config_expanded_js_1 = require("../config/postcss.config.expanded.js"); +const postcss_config_compressed_js_1 = require("../config/postcss.config.compressed.js"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * Class responsible for processing styles, including compiling SCSS and + * applying PostCSS transformations. + */ +class StyleProcessor { + /** + * Processes the given CSS with PostCSS based on the provided style option. + * @param css The CSS string to process. + * @param styleOption The style option, either 'expanded' or 'compressed'. + * @returns Processed CSS string. + */ + processPostCSS(css, styleOption) { + return __awaiter(this, void 0, void 0, function* () { + const config = styleOption === 'expanded' ? postcss_config_expanded_js_1.default : postcss_config_compressed_js_1.default; + return (0, postcss_1.default)(config.plugins).process(css, { from: undefined, map: { inline: false } }); + }); + } + /** + * Compiles SCSS to CSS and processes it using PostCSS. + * @param inputFile Path to the input SCSS file. + * @param outputFile Path to the output CSS file. + * @param styleOption Style option for the output. + */ + processStyles(inputFile, outputFile, styleOption) { + return __awaiter(this, void 0, void 0, function* () { + try { + // Compile SCSS to CSS + const result = yield sass.compileAsync(inputFile, { style: styleOption }); + // Process the compiled CSS with PostCSS and Autoprefixer + const processed = yield this.processPostCSS(result.css, styleOption); + // Write the processed CSS to a file + fs_1.default.writeFileSync(outputFile, processed.css); + // Write the source map file + if (processed.map) { + fs_1.default.writeFileSync(`${outputFile}.map`, processed.map.toString()); + } + } + catch (err) { + // Handle errors in the compilation or processing + console.error(`Error processing styles from ${inputFile}:`, err); + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = StyleProcessor; diff --git a/dist/js/class/SvgPackager.js b/dist/js/class/SvgPackager.js new file mode 100644 index 0000000..d7086de --- /dev/null +++ b/dist/js/class/SvgPackager.js @@ -0,0 +1,191 @@ +"use strict"; +// class/SvgPackager.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +// import * as fs from 'fs'; +const fs_extra = require("fs-extra"); +const fs_1 = require("fs"); +const glob = require("glob"); +const path = require("path"); +const url_1 = require("url"); +const svgo_1 = require("svgo"); +const svgo_2 = require("svgo"); +// Convert the current file's URL to a file path +const __filename = (0, url_1.fileURLToPath)(import.meta.url); +// Derive the directory name of the current module +const __dirname = path.dirname(__filename); +// ============================================================================ +// Classes +// ============================================================================ +/** + * Class for packaging SVG files. + * This class reads SVG files from a specified directory, optimizes them, + * and creates corresponding TypeScript files. + */ +class SvgPackager { + /** + * Processes all SVG files in a given directory. + * @param directory The directory containing SVG files to process. + * @param outputDirectory The directory where optimized SVGs will be output as TypeScript files. + */ + processSvgFiles(directory, outputDirectory, ts_output_directory, json_output_directory) { + return __awaiter(this, void 0, void 0, function* () { + const iconNames = []; + try { + console.log(`Processing directory: ${directory}`); + const svgFiles = glob.sync(`${directory}/**/*.svg`); + for (const file of svgFiles) { + console.log(`Processing file: ${file}`); + const iconName = this.sanitizeFileName(path.basename(file, '.svg')); + iconNames.push(iconName); + console.log(`Processing icon: ${iconName}`); + const svgContent = yield this.readSvgFile(file); + const optimizedSvg = yield this.optimizeSvg(file, svgContent); + // svgo will always add a final newline when in pretty mode + const resultSvg = optimizedSvg.trim(); + // Write the optimized SVG file + yield this.writeSvgFile(file, iconName, resultSvg, outputDirectory); + // Write the optimized TypeScript file + yield this.writeTypeScriptFile(file, iconName, resultSvg, ts_output_directory); + } + yield this.writeIconsJson(iconNames, json_output_directory); + console.log(`Successfully processed ${svgFiles.length} SVG files.`); + } + catch (error) { + console.error('Error processing SVG files:', error); + throw error; + } + }); + } + /** + * Reads the content of an SVG file. + * @param filePath The path to the SVG file. + * @returns The content of the SVG file. + */ + readSvgFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const absolutePath = path.resolve(filePath); + const svgContent = yield fs_1.promises.readFile(absolutePath, 'utf8'); + return svgContent; + } + catch (error) { + console.error('Error reading file:', filePath, error); + throw error; + } + }); + } + /** + * Sanitizes a file name to be a valid TypeScript identifier. + * @param fileName The original file name. + * @returns A sanitized version of the file name. + */ + sanitizeFileName(fileName) { + // Implement more robust sanitization logic if necessary + return fileName.replace(/[^a-zA-Z0-9_]/g, '_'); + } + /** + * Optimizes SVG content using SVGO. + * @param svgContent The raw SVG content. + * @returns The optimized SVG content. + */ + optimizeSvg(filePath, svgContent) { + return __awaiter(this, void 0, void 0, function* () { + try { + const config = yield (0, svgo_2.loadConfig)(path.join(__dirname, '../config/svgo.config.js')); + const result = yield svgo_1.default.optimize(svgContent, Object.assign({ path: filePath }, config)); + return result.data; + } + catch (error) { + console.error('Error optimizing SVG:', error); + throw error; + } + }); + } + /** + * Creates a TypeScript file from SVG content. + * @param filePath The path of the SVG file. + * @param svgContent The optimized SVG content. + * @param outputDirectory The directory to output the TypeScript file. + */ + writeTypeScriptFile(filePath, iconName, svgContent, outputDirectory) { + return __awaiter(this, void 0, void 0, function* () { + try { + const tsContent = `export const icon_${iconName} = \`${svgContent}\`;\n`; + const outputPath = path.join(outputDirectory, `${iconName}.ts`); + yield fs_extra.outputFile(outputPath, tsContent); + } + catch (error) { + console.error(`Error creating TypeScript file for ${filePath}:`, error); + throw error; + } + }); + } + /** + * Writes the SVG content to a file. + * @param filePath The original file path of the SVG. + * @param svgContent The SVG content to be written. + * @param outputDirectory The directory to output the SVG file. + */ + writeSvgFile(filePath, iconName, svgContent, outputDirectory) { + return __awaiter(this, void 0, void 0, function* () { + try { + const outputPath = path.join(outputDirectory, `${iconName}.svg`); + yield fs_extra.outputFile(outputPath, svgContent); + console.log(`SVG file written successfully for ${iconName}`); + } + catch (error) { + console.error(`Error writing SVG file for ${iconName}:`, error); + throw error; + } + }); + } + /** + * Writes a JSON file containing the names of processed icons. + * This method creates a JSON file that lists all icon names which have + * been processed, making it easier to reference or index these icons in + * other parts of an application. + * + * @param iconNames An array of strings containing the names of the icons. + * @param outputDirectory The directory where the JSON file will be saved. + */ + writeIconsJson(iconNames, outputDirectory) { + return __awaiter(this, void 0, void 0, function* () { + try { + const jsonContent = JSON.stringify(iconNames, null, 2); + const outputPath = path.join(outputDirectory, 'icons.json'); + yield fs_extra.outputFile(outputPath, jsonContent); + console.log('Icons JSON file created successfully'); + } + catch (error) { + console.error('Error writing icons JSON file:', error); + throw error; + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = SvgPackager; diff --git a/dist/js/class/SvgSpriteGenerator.js b/dist/js/class/SvgSpriteGenerator.js new file mode 100644 index 0000000..0638a4c --- /dev/null +++ b/dist/js/class/SvgSpriteGenerator.js @@ -0,0 +1,82 @@ +"use strict"; +// class/SvgSpriteGenerator.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const svg_sprite_1 = require("svg-sprite"); +const fs_1 = require("fs"); +const path_1 = require("path"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for generating SVG sprites from individual SVG files. + */ +class SvgSpriteGenerator { + /** + * Constructs an instance of SvgSpriteGenerator with the provided configuration. + * @param {any} config - Configuration object for svg-sprite. + */ + constructor(config) { + this.config = config; + } + /** + * Generates an SVG sprite from SVG files in a specified directory. + * @param {string} sourceDir - Directory containing source SVG files. + * @param {string} outputDir - Directory where the generated sprite will be saved. + */ + generateSprite(sourceDir, outputDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const files = fs_1.default.readdirSync(sourceDir); + const sprite = new svg_sprite_1.default(this.config); + files.forEach(file => { + if (path_1.default.extname(file) === '.svg') { + const svgPath = path_1.default.resolve(sourceDir, file); + const content = fs_1.default.readFileSync(svgPath, 'utf8'); + sprite.add(svgPath, null, content); + } + }); + sprite.compile((error, result) => { + if (error) { + throw error; + } + for (const mode in result) { + for (const resource in result[mode]) { + const outputPath = path_1.default.resolve(outputDir, result[mode][resource].path); + fs_1.default.mkdirSync(path_1.default.dirname(outputPath), { recursive: true }); + fs_1.default.writeFileSync(outputPath, result[mode][resource].contents); + } + } + }); + } + catch (err) { + console.error('Error generating SVG sprite:', err); + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = SvgSpriteGenerator; diff --git a/dist/js/class/TypeScriptCompiler.js b/dist/js/class/TypeScriptCompiler.js new file mode 100644 index 0000000..9b26a2a --- /dev/null +++ b/dist/js/class/TypeScriptCompiler.js @@ -0,0 +1,83 @@ +"use strict"; +// class/TypeScriptCompiler.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +// import * as ts from 'typescript'; +const typescript_1 = require("typescript"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * TypeScriptCompiler class for compiling TypeScript files to JavaScript. + */ +class TypeScriptCompiler { + /** + * Constructs an instance with the provided configuration. + * @param {any} config - Configuration object + */ + constructor(config) { + this.config = config; + } + /** + * Compiles TypeScript files to JavaScript. + * + * @param {string[]} filePaths - The paths of TypeScript files to be compiled. + * @param {string} outDir - The directory where the compiled JavaScript files will be saved. + * @param {ts.CompilerOptions} customOptions - Optional custom TypeScript compiler options. + * + * This method sets up a TypeScript program with given file paths and compiler options. + * It handles the compilation of TypeScript files into JavaScript, considering any provided custom options. + * Compilation errors and diagnostics are logged for debugging purposes. + * The method returns a promise that resolves when compilation is successful or rejects in case of errors. + */ + compile(filePaths, outDir) { + return new Promise((resolve, reject) => { + // Merge default options with custom options + const options = Object.assign({ module: typescript_1.default.ModuleKind.CommonJS, target: typescript_1.default.ScriptTarget.ES2015, outDir }, this.config); + // Create a TypeScript compiler host + const host = typescript_1.default.createCompilerHost(options); + // Create a program with the specified files and options + const program = typescript_1.default.createProgram(filePaths, options, host); + // Emit the compiled JavaScript files + const emitResult = program.emit(); + // Check for compilation errors + const allDiagnostics = typescript_1.default.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + allDiagnostics.forEach(diagnostic => { + // Handle and print diagnostics + if (diagnostic.file) { + const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + const message = typescript_1.default.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + } + else { + console.error(typescript_1.default.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + }); + const exitCode = emitResult.emitSkipped ? 1 : 0; + if (exitCode === 0) { + console.log('Compilation completed successfully.'); + resolve(); + } + else { + console.error('Compilation failed.'); + reject(new Error('TypeScript compilation failed')); + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = TypeScriptCompiler; diff --git a/dist/js/class/VersionWriter.js b/dist/js/class/VersionWriter.js new file mode 100644 index 0000000..3070397 --- /dev/null +++ b/dist/js/class/VersionWriter.js @@ -0,0 +1,54 @@ +"use strict"; +// class/VersionWriter.ts +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const fs_1 = require("fs"); +// ============================================================================ +// Classes +// ============================================================================ +/** + * A class for writing version information to a file. + */ +class VersionWriter { + /** + * Writes the specified version string to a file. + * @param {string} filePath - The file path where the version will be written. + * @param {string} version - The version string to write to the file. + */ + writeVersionToFile(filePath, version) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield fs_1.promises.writeFile(filePath, version, 'utf8'); + console.log(`Version ${version} written to ${filePath}`); + } + catch (error) { + console.error(`Error writing version to file: ${error}`); + } + }); + } +} +// ============================================================================ +// Export +// ============================================================================ +exports.default = VersionWriter; diff --git a/dist/js/config/config.js b/dist/js/config/config.js new file mode 100644 index 0000000..0f1d507 --- /dev/null +++ b/dist/js/config/config.js @@ -0,0 +1,37 @@ +"use strict"; +// config/config.ts +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CONFIG = void 0; +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +exports.CONFIG = { + path: { + src: './src', + dist: './dist', + svg_input: './src/svg', + svg_output: './dist/svg', + sprite_input: './dist/svg', + sprite_output: './dist/sprite', + font_input: './dist/svg', + font_output: './dist/font', + scss_input: './src/scss', + scss_output: './dist/scss', + css_output: './dist/css', + json_output: './dist', + ts_input: './src/ts', + ts_output: './dist/ts', + ts_output_icons: './src/ts/icons', + js_output: './dist/js', + }, +}; diff --git a/dist/js/config/package.config.js b/dist/js/config/package.config.js new file mode 100644 index 0000000..03826a3 --- /dev/null +++ b/dist/js/config/package.config.js @@ -0,0 +1,62 @@ +"use strict"; +// config/package.config.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const pack_object = require("../../../package.json"); +const pack = JSON.parse(JSON.stringify(pack_object)).default; // req.body = [Object: null prototype] { title: 'product' } +const packageConfig = { + name: pack.name, + version: pack.version, + description: pack.description, + keywords: pack.keywords, + license: pack.license, + homepage: pack.homepage, + main: 'index.js', + files: [ + "svg/**/*.{svg}", + "js/**/*.{js,map}", + "ts/**/*.ts", + "css/**/*.{css,map}", + "scss/**/*.{scss}", + "font/**/*.{eot,otf,ttf,woff,woff2}", + "!.DS_Store" + ], + // repository: { + // type: pack.repository.type, + // url: pack.repository.url, + // }, + // author?: string | { + // name: string; + // email?: string; + // url?: string; + // }; + // bugs?: { + // url?: string; + // email?: string; + // }; + // contributors?: Array; + // funding?: string | { + // type: string; + // url: string; + // }; +}; +// ============================================================================ +// Export +// ============================================================================ +exports.default = packageConfig; diff --git a/dist/js/config/postcss.config.compressed.js b/dist/js/config/postcss.config.compressed.js new file mode 100644 index 0000000..11eb053 --- /dev/null +++ b/dist/js/config/postcss.config.compressed.js @@ -0,0 +1,34 @@ +"use strict"; +// config/postcss.config.compressed.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const autoprefixer_1 = require("autoprefixer"); +const cssnano_1 = require("cssnano"); +// ============================================================================ +// Constants +// ============================================================================ +const postcssConfigCompressed = { + plugins: [ + autoprefixer_1.default, + // Minification for compressed output + (0, cssnano_1.default)({ + preset: 'default' + }), + ] +}; +// ============================================================================ +// Export +// ============================================================================ +exports.default = postcssConfigCompressed; diff --git a/dist/js/config/postcss.config.expanded.js b/dist/js/config/postcss.config.expanded.js new file mode 100644 index 0000000..9561430 --- /dev/null +++ b/dist/js/config/postcss.config.expanded.js @@ -0,0 +1,30 @@ +"use strict"; +// config/postcss.config.expanded.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +const autoprefixer_1 = require("autoprefixer"); +// ============================================================================ +// Constants +// ============================================================================ +const postcssConfigExpanded = { + plugins: [ + autoprefixer_1.default, + // Include other plugins suited for the expanded output + ] +}; +// ============================================================================ +// Export +// ============================================================================ +exports.default = postcssConfigExpanded; diff --git a/dist/js/config/svgsprite.config.js b/dist/js/config/svgsprite.config.js new file mode 100644 index 0000000..30be997 --- /dev/null +++ b/dist/js/config/svgsprite.config.js @@ -0,0 +1,109 @@ +"use strict"; +// config/svg-sprite.config.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// ============================================================================ +// Constants +// ============================================================================ +const svgspriteConfig = { + dest: './dist/sprite', // Main output directory + // log: null, // Logging verbosity (default: no logging) + shape: { + id: { + separator: '--', // Separator for directory name traversal + generator: 'icon-%s', + // generator: function () { /*...*/ }, // SVG shape ID generator callback + pseudo: '~' // File name separator for shape states (e.g. ':hover') + }, + dimension: { + maxWidth: 2000, // Max. shape width + maxHeight: 2000, // Max. shape height + precision: 2, // Floating point precision + attributes: false, // Width and height attributes on embedded shapes + }, + spacing: { + padding: 0, // Padding around all shapes + box: 'content' // Padding strategy (similar to CSS `box-sizing`) + }, + transform: ['svgo'], // List of transformations / optimizations + // meta: null, // Path to YAML file with meta / accessibility data + // align: null, // Path to YAML file with extended alignment data + // dest: null // Output directory for optimized intermediate SVG shapes + }, + svg: { + xmlDeclaration: false, // Add XML declaration to SVG sprite + // xmlDeclaration: true, // Add XML declaration to SVG sprite + doctypeDeclaration: true, // Add DOCTYPE declaration to SVG sprite + namespaceIDs: true, // Add namespace token to all IDs in SVG shapes + // namespaceIDPrefix: '', // Add a prefix to the automatically generated namespaceIDs + // namespaceClassnames: true, // Add namespace token to all CSS class names in SVG shapes + namespaceClassnames: false, // Add namespace token to all CSS class names in SVG shapes + dimensionAttributes: true // Width and height attributes on the sprite + }, + variables: {}, // Custom Mustache templating variables and functions + mode: { + css: { + render: { + css: true // Render CSS stylesheet + } + }, + view: true, // Create a «view» sprite + defs: true, // Create a «defs» sprite + // symbol: true, // Create a «symbol» sprite + symbol: { + // dest: ".", + // inline: true, // Prepare for inline embedding + sprite: "icon.gl.svg" + }, + stack: true, // Create a «stack» sprite + // symbol: true // Symbol sprite mode + } +}; +// ============================================================================ +// Export +// ============================================================================ +exports.default = svgspriteConfig; +// "svgo": { +// "multipass": true, +// "plugins": [ +// { +// "name": "preset-default", +// "params": { +// "overrides": { +// "removeUnknownsAndDefaults": { +// "keepDataAttrs": false, +// "keepRoleAttr": true +// }, +// "removeViewBox": false +// } +// } +// }, +// "cleanupListOfValues", +// "removeXMLNS", +// { +// "name": "removeAttrs", +// "params": { +// "attrs": [ +// "clip-rule", +// "fill" +// ] +// } +// } +// ] +// } +// : { +// dest: "", // Mode specific output directory +// prefix: "svg-%s", // Prefix for CSS selectors +// dimensions: "-dims", // Suffix for dimension CSS selectors +// sprite: "svg/sprite..svg", // Sprite path and name +// bust: true || false, // Cache busting (mode dependent default value) +// render: { // Stylesheet rendering definitions +// /* ------------------------------------------- +// css: false, // CSS stylesheet options +// scss: false, // Sass stylesheet options +// less: false, // LESS stylesheet options +// styl: false, // Stylus stylesheet options +// : ... // Custom stylesheet options +// ------------------------------------------- */ +// }, +// example: false // Create an HTML example document +// } diff --git a/dist/js/config/terser.config.js b/dist/js/config/terser.config.js new file mode 100644 index 0000000..db82f8b --- /dev/null +++ b/dist/js/config/terser.config.js @@ -0,0 +1,130 @@ +"use strict"; +// config/terser.config.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +// ============================================================================ +// Constants +// ============================================================================ +// https://terser.org/docs/api-reference/ +const terserConfig = { + parse: { + // parse options + }, + compress: { + // compress options + drop_console: true, // Remove console.log statements + drop_debugger: true, // Remove debugger statements + pure_funcs: ['console.info', 'console.debug', 'console.warn'], // Remove specific console functions + // defaults (default: true) -- Pass false to disable most default enabled compress transforms. Useful when you only want to enable a few compress options while disabling the rest. + // Class and object literal methods are converted will also be + // converted to arrow expressions if the resultant code is shorter: + // m(){return x} becomes m:()=>x. To do this to regular ES5 functions + // which don't use this or arguments, see unsafe_arrows. + arrows: true, // (default: true) + // arguments (default: false) -- replace arguments[index] with function parameter name whenever possible. + // booleans (default: true) -- various optimizations for boolean context, for example !!a ? b : c → a ? b : c + // booleans_as_integers (default: false) -- Turn booleans into 0 and 1, also makes comparisons with booleans use == and != instead of === and !==. + // collapse_vars (default: true) -- Collapse single-use non-constant variables, side effects permitting. + // comparisons (default: true) -- apply certain optimizations to binary nodes, e.g. !(a <= b) → a > b (only when unsafe_comps), attempts to negate binary nodes, e.g. a = !b && !c && !d && !e → a=!(b||c||d||e) etc. Note: comparisons works best with lhs_constants enabled. + // computed_props (default: true) -- Transforms constant computed properties into regular ones: {["computed"]: 1} is converted to {computed: 1}. + // conditionals (default: true) -- apply optimizations for if-s and conditional expressions + // dead_code (default: true) -- remove unreachable code + // directives (default: true) -- remove redundant or non-standard directives + // drop_console (default: false) -- Pass true to discard calls to console.* functions. If you only want to discard a portion of console, you can pass an array like this ['log', 'info'], which will only discard console.log、 console.info. + // drop_debugger (default: true) -- remove debugger; statements + // ecma (default: 5) -- Pass 2015 or greater to enable compress options that will transform ES5 code into smaller ES6+ equivalent forms. + // evaluate (default: true) -- attempt to evaluate constant expressions + // expression (default: false) -- Pass true to preserve completion values from terminal statements without return, e.g. in bookmarklets. + // global_defs (default: {}) -- see conditional compilation + // hoist_funs (default: false) -- hoist function declarations + // hoist_props (default: true) -- hoist properties from constant object and array literals into regular variables subject to a set of constraints. For example: var o={p:1, q:2}; f(o.p, o.q); is converted to f(1, 2);. Note: hoist_props works best with mangle enabled, the compress option passes set to 2 or higher, and the compress option toplevel enabled. + // hoist_vars (default: false) -- hoist var declarations (this is false by default because it seems to increase the size of the output in general) + // if_return (default: true) -- optimizations for if/return and if/continue + // inline (default: true) -- inline calls to function with simple/return statement: + // false -- same as 0 + // 0 -- disabled inlining + // 1 -- inline simple functions + // 2 -- inline functions with arguments + // 3 -- inline functions with arguments and variables + // true -- same as 3 + // join_vars (default: true) -- join consecutive var, let and const statements + // keep_classnames (default: false) -- Pass true to prevent the compressor from discarding class names. Pass a regular expression to only keep class names matching that regex. See also: the keep_classnames mangle option. + // keep_fargs (default: true) -- Prevents the compressor from discarding unused function arguments. You need this for code which relies on Function.length. + // keep_fnames (default: false) -- Pass true to prevent the compressor from discarding function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying on Function.prototype.name. See also: the keep_fnames mangle option. + // keep_infinity (default: false) -- Pass true to prevent Infinity from being compressed into 1/0, which may cause performance issues on Chrome. + // lhs_constants (default: true) -- Moves constant values to the left-hand side of binary nodes. foo == 42 → 42 == foo + // loops (default: true) -- optimizations for do, while and for loops when we can statically determine the condition. + // module (default false) -- Pass true when compressing an ES6 module. Strict mode is implied and the toplevel option as well. + // negate_iife (default: true) -- negate "Immediately-Called Function Expressions" where the return value is discarded, to avoid the parens that the code generator would insert. + // passes (default: 1) -- The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. + // properties (default: true) -- rewrite property access using the dot notation, for example foo["bar"] → foo.bar + // pure_funcs (default: null) -- You can pass an array of names and Terser will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instance var q = Math.floor(a/b). If variable q is not used elsewhere, Terser will drop it, but will still keep the Math.floor(a/b), not knowing what it does. You can pass pure_funcs: [ 'Math.floor' ] to let it know that this function won't produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower). + // pure_getters (default: "strict") -- If you pass true for this, Terser will assume that object property access (e.g. foo.bar or foo["bar"]) doesn't have any side effects. Specify "strict" to treat foo.bar as side-effect-free only when foo is certain to not throw, i.e. not null or undefined. + // pure_new (default: false) -- Set to true to assume new X() never has side effects. + // reduce_vars (default: true) -- Improve optimization on variables assigned with and used as constant values. + // reduce_funcs (default: true) -- Inline single-use functions when possible. Depends on reduce_vars being enabled. Disabling this option sometimes improves performance of the output code. + // sequences (default: true) -- join consecutive simple statements using the comma operator. May be set to a positive integer to specify the maximum number of consecutive comma sequences that will be generated. If this option is set to true then the default sequences limit is 200. Set option to false or 0 to disable. The smallest sequences length is 2. A sequences value of 1 is grandfathered to be equivalent to true and as such means 200. On rare occasions the default sequences limit leads to very slow compress times in which case a value of 20 or less is recommended. + // side_effects (default: true) -- Remove expressions which have no side effects and whose results aren't used. + // switches (default: true) -- de-duplicate and remove unreachable switch branches + // toplevel (default: false) -- drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (false by default, true to drop both unreferenced functions and variables) + // top_retain (default: null) -- prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel) + // typeofs (default: true) -- Transforms typeof foo == "undefined" into foo === void 0. Note: recommend to set this value to false for IE10 and earlier versions due to known issues. + // unsafe (default: false) -- apply "unsafe" transformations (details). + // unsafe_arrows (default: false) -- Convert ES5 style anonymous function expressions to arrow functions if the function body does not reference this. Note: it is not always safe to perform this conversion if code relies on the the function having a prototype, which arrow functions lack. This transform requires that the ecma compress option is set to 2015 or greater. + // unsafe_comps (default: false) -- Reverse < and <= to > and >= to allow improved compression. This might be unsafe when an at least one of two operands is an object with computed values due the use of methods like get, or valueOf. This could cause change in execution order after operands in the comparison are switching. Compression only works if both comparisons and unsafe_comps are both set to true. + // unsafe_Function (default: false) -- compress and mangle Function(args, code) when both args and code are string literals. + // unsafe_math (default: false) -- optimize numerical expressions like 2 * x * 3 into 6 * x, which may give imprecise floating point results. + // unsafe_symbols (default: false) -- removes keys from native Symbol declarations, e.g Symbol("kDog") becomes Symbol(). + // unsafe_methods (default: false) -- Converts { m: function(){} } to { m(){} }. ecma must be set to 6 or greater to enable this transform. If unsafe_methods is a RegExp then key/value pairs with keys matching the RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a " is not a constructor" TypeError should any code try to new the former function. + // unsafe_proto (default: false) -- optimize expressions like Array.prototype.slice.call(a) into [].slice.call(a) + // unsafe_regexp (default: false) -- enable substitutions of variables with RegExp values the same way as if they are constants. + // unsafe_undefined (default: false) -- substitute void 0 if there is a variable named undefined in scope (variable name will be mangled, typically reduced to a single character) + // unused (default: true) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to "keep_assign") + }, + mangle: { + // mangle options + // Mangle names for obfuscation and size reduction + // properties: true, // Mangle property names + properties: { + // mangle property options + bare_returns: false, //support top level return statements + html5_comments: true, // (default true) + shebang: true, //(default true) -- support #!command as the first line + spidermonkey: false, // (default false) -- accept a Spidermonkey (Mozilla) AST + } + }, + format: { + // format options (can also use `output` for backwards compatibility) + comments: false, // Remove comments to reduce file size + beautify: false, // Disable beautification for smaller file size + }, + sourceMap: { + // source map options + }, + // Define ECMAScript target version + ecma: 5, // specify one of: 5, 2015, 2016, etc. + enclose: false, // or specify true, or "args:values" + keep_classnames: false, // Remove class names + keep_fnames: false, // Remove function names + ie8: false, + module: false, + nameCache: null, // or specify a name cache object + safari10: false, + toplevel: true, // Enable top-level variable and function name mangling +}; +// ============================================================================ +// Export +// ============================================================================ +exports.default = terserConfig; diff --git a/dist/js/config/ts.config.js b/dist/js/config/ts.config.js new file mode 100644 index 0000000..76acd0e --- /dev/null +++ b/dist/js/config/ts.config.js @@ -0,0 +1,129 @@ +"use strict"; +// config/ts.config.ts +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +// ============================================================================ +// Constants +// ============================================================================ +const tsConfig = { +// allowImportingTsExtensions?: boolean; +// allowJs?: boolean; +// allowArbitraryExtensions?: boolean; +// allowSyntheticDefaultImports?: boolean; +// allowUmdGlobalAccess?: boolean; +// allowUnreachableCode?: boolean; +// allowUnusedLabels?: boolean; +// alwaysStrict?: boolean; +// baseUrl?: string; +// charset?: string; +// checkJs?: boolean; +// customConditions?: string[]; +// declaration?: boolean; +// declarationMap?: boolean; +// emitDeclarationOnly?: boolean; +// declarationDir?: string; +// disableSizeLimit?: boolean; +// disableSourceOfProjectReferenceRedirect?: boolean; +// disableSolutionSearching?: boolean; +// disableReferencedProjectLoad?: boolean; +// downlevelIteration?: boolean; +// emitBOM?: boolean; +// emitDecoratorMetadata?: boolean; +// exactOptionalPropertyTypes?: boolean; +// experimentalDecorators?: boolean; +// forceConsistentCasingInFileNames?: boolean; +// ignoreDeprecations?: string; +// importHelpers?: boolean; +// importsNotUsedAsValues?: ImportsNotUsedAsValues; +// inlineSourceMap?: boolean; +// inlineSources?: boolean; +// isolatedModules?: boolean; +// jsx?: JsxEmit; +// keyofStringsOnly?: boolean; +// lib?: string[]; +// locale?: string; +// mapRoot?: string; +// maxNodeModuleJsDepth?: number; +// module?: ModuleKind; +// moduleResolution?: ModuleResolutionKind; +// moduleSuffixes?: string[]; +// moduleDetection?: ModuleDetectionKind; +// newLine?: NewLineKind; +// noEmit?: boolean; +// noEmitHelpers?: boolean; +// noEmitOnError?: boolean; +// noErrorTruncation?: boolean; +// noFallthroughCasesInSwitch?: boolean; +// noImplicitAny?: boolean; +// noImplicitReturns?: boolean; +// noImplicitThis?: boolean; +// noStrictGenericChecks?: boolean; +// noUnusedLocals?: boolean; +// noUnusedParameters?: boolean; +// noImplicitUseStrict?: boolean; +// noPropertyAccessFromIndexSignature?: boolean; +// assumeChangesOnlyAffectDirectDependencies?: boolean; +// noLib?: boolean; +// noResolve?: boolean; +// noUncheckedIndexedAccess?: boolean; +// out?: string; +// outDir?: string; +// outFile: 'icon.gl.js' // string; +// paths?: MapLike; +// preserveConstEnums?: boolean; +// noImplicitOverride?: boolean; +// preserveSymlinks?: boolean; +// preserveValueImports?: boolean; +// project?: string; +// reactNamespace?: string; +// jsxFactory?: string; +// jsxFragmentFactory?: string; +// jsxImportSource?: string; +// composite?: boolean; +// incremental?: boolean; +// tsBuildInfoFile?: string; +// removeComments?: boolean; +// resolvePackageJsonExports?: boolean; +// resolvePackageJsonImports?: boolean; +// rootDir?: string; +// rootDirs?: string[]; +// skipLibCheck?: boolean; +// skipDefaultLibCheck?: boolean; +// sourceMap?: boolean; +// sourceRoot?: string; +// strict?: boolean; +// strictFunctionTypes?: boolean; +// strictBindCallApply?: boolean; +// strictNullChecks?: boolean; +// strictPropertyInitialization?: boolean; +// stripInternal?: boolean; +// suppressExcessPropertyErrors?: boolean; +// suppressImplicitAnyIndexErrors?: boolean; +// target?: ScriptTarget; +// traceResolution?: boolean; +// useUnknownInCatchVariables?: boolean; +// resolveJsonModule?: boolean; +// types?: string[]; +// /** Paths used to compute primary types search locations */ +// typeRoots?: string[]; +// verbatimModuleSyntax?: boolean; +// esModuleInterop?: boolean; +// useDefineForClassFields?: boolean; +// [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; +}; +// ============================================================================ +// Export +// ============================================================================ +exports.default = tsConfig; diff --git a/dist/js/pack.gl.js b/dist/js/pack.gl.js new file mode 100644 index 0000000..1b460d5 --- /dev/null +++ b/dist/js/pack.gl.js @@ -0,0 +1,45 @@ +"use strict"; +// script/index.ts +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JavaScriptMinifier = exports.TypeScriptCompiler = exports.VersionWriter = exports.SvgSpriteGenerator = exports.StyleProcessor = exports.SvgPackager = exports.PackageCreator = exports.FontGenerator = exports.FileRenamer = exports.FileCopier = exports.DirectoryCreator = exports.DirectoryCopier = exports.DirectoryCleaner = void 0; +// Copyright 2023 Scape Agency BV +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================ +// Import +// ============================================================================ +// Import | Utility Classes +const DirectoryCleaner_1 = require("./class/DirectoryCleaner"); +exports.DirectoryCleaner = DirectoryCleaner_1.default; +const DirectoryCopier_1 = require("./class/DirectoryCopier"); +exports.DirectoryCopier = DirectoryCopier_1.default; +const DirectoryCreator_1 = require("./class/DirectoryCreator"); +exports.DirectoryCreator = DirectoryCreator_1.default; +const FileCopier_js_1 = require("./class/FileCopier.js"); +exports.FileCopier = FileCopier_js_1.default; +const FileRenamer_js_1 = require("./class/FileRenamer.js"); +exports.FileRenamer = FileRenamer_js_1.default; +// Import | Internal Classes +const FontGenerator_js_1 = require("./class/FontGenerator.js"); +exports.FontGenerator = FontGenerator_js_1.default; +const PackageCreator_js_1 = require("./class/PackageCreator.js"); +exports.PackageCreator = PackageCreator_js_1.default; +const SvgPackager_js_1 = require("./class/SvgPackager.js"); +exports.SvgPackager = SvgPackager_js_1.default; +const StyleProcessor_js_1 = require("./class/StyleProcessor.js"); +exports.StyleProcessor = StyleProcessor_js_1.default; +const SvgSpriteGenerator_js_1 = require("./class/SvgSpriteGenerator.js"); +exports.SvgSpriteGenerator = SvgSpriteGenerator_js_1.default; +const VersionWriter_js_1 = require("./class/VersionWriter.js"); +exports.VersionWriter = VersionWriter_js_1.default; +const TypeScriptCompiler_js_1 = require("./class/TypeScriptCompiler.js"); +exports.TypeScriptCompiler = TypeScriptCompiler_js_1.default; +const JavaScriptMinifier_js_1 = require("./class/JavaScriptMinifier.js"); +exports.JavaScriptMinifier = JavaScriptMinifier_js_1.default; diff --git a/dist/js/pack.gl.min.js b/dist/js/pack.gl.min.js new file mode 100644 index 0000000..3e4d129 --- /dev/null +++ b/dist/js/pack.gl.min.js @@ -0,0 +1 @@ +"use strict";Object.defineProperty(exports,"o",{value:!0}),exports.JavaScriptMinifier=exports.TypeScriptCompiler=exports.VersionWriter=exports.SvgSpriteGenerator=exports.StyleProcessor=exports.SvgPackager=exports.PackageCreator=exports.FontGenerator=exports.FileRenamer=exports.FileCopier=exports.DirectoryCreator=exports.DirectoryCopier=exports.DirectoryCleaner=void 0;const e=require("./class/DirectoryCleaner");exports.DirectoryCleaner=e.default;const r=require("./class/DirectoryCopier");exports.DirectoryCopier=r.default;const s=require("./class/DirectoryCreator");exports.DirectoryCreator=s.default;const o=require("./class/FileCopier.js");exports.FileCopier=o.default;const t=require("./class/FileRenamer.js");exports.FileRenamer=t.default;const c=require("./class/FontGenerator.js");exports.FontGenerator=c.default;const p=require("./class/PackageCreator.js");exports.PackageCreator=p.default;const i=require("./class/SvgPackager.js");exports.SvgPackager=i.default;const x=require("./class/StyleProcessor.js");exports.StyleProcessor=x.default;const a=require("./class/SvgSpriteGenerator.js");exports.SvgSpriteGenerator=a.default;const l=require("./class/VersionWriter.js");exports.VersionWriter=l.default;const n=require("./class/TypeScriptCompiler.js");exports.TypeScriptCompiler=n.default;const u=require("./class/JavaScriptMinifier.js");exports.JavaScriptMinifier=u.default; \ No newline at end of file diff --git a/dist/package.json b/dist/package.json new file mode 100644 index 0000000..91ef318 --- /dev/null +++ b/dist/package.json @@ -0,0 +1,24 @@ +{ + "name": "pack.gl", + "version": "0.0.1", + "description": "Package Builder.", + "keywords": [ + "pack.gl", + "pack", + "packager", + "framework", + "web" + ], + "license": "Apache-2.0", + "homepage": "https://www.pack.gl/", + "main": "index.js", + "files": [ + "svg/**/*.svg", + "js/**/*.{js,map}", + "ts/**/*.ts", + "css/**/*.{css,map}", + "scss/**/*.scss", + "font/**/*.{eot,otf,ttf,woff,woff2}", + "!.DS_Store" + ] +} \ No newline at end of file diff --git a/dist/ts/class/DirectoryCleaner.ts b/dist/ts/class/DirectoryCleaner.ts new file mode 100644 index 0000000..9516070 --- /dev/null +++ b/dist/ts/class/DirectoryCleaner.ts @@ -0,0 +1,65 @@ +// class/DirectoryCleaner.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { promises as fsPromises } from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +class DirectoryCleaner { + + /** + * Recursively deletes all contents of the directory asynchronously. + * @param dirPath The path to the directory to clean. + */ + public async cleanDirectory(dirPath: string): Promise { + try { + const files = await fsPromises.readdir(dirPath); + + for (const file of files) { + const curPath = path.join(dirPath, file); + const stat = await fsPromises.lstat(curPath); + + if (stat.isDirectory()) { + await this.cleanDirectory(curPath); + } else { + await fsPromises.unlink(curPath); + } + } + + await fsPromises.rmdir(dirPath); + } catch (error) { + console.error(`Error cleaning directory ${dirPath}: ${error}`); + throw error; // Rethrow the error for further handling if necessary + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default DirectoryCleaner; diff --git a/dist/ts/class/DirectoryCopier.ts b/dist/ts/class/DirectoryCopier.ts new file mode 100644 index 0000000..f91be2c --- /dev/null +++ b/dist/ts/class/DirectoryCopier.ts @@ -0,0 +1,80 @@ +// class/DirectoryCopier.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; +import { promises as fsPromises } from 'fs'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for copying files from one directory to another. + */ +class DirectoryCopier { + + /** + * Copies all files and subdirectories from a source directory to a destination directory. + * @param srcDir The source directory path. + * @param destDir The destination directory path. + * @throws Will throw an error if copying fails for any file or directory. + */ + async copyFiles(srcDir: string, destDir: string): Promise { + try { + const resolvedSrcDir = path.resolve(srcDir); + const resolvedDestDir = path.resolve(destDir); + await this.recursiveCopy(resolvedSrcDir, resolvedDestDir); + console.log(`Files copied from ${resolvedSrcDir} to ${resolvedDestDir}`); + } catch (error) { + console.error('Error copying files:', error); + throw error; + } + } + + /** + * Recursively copies files and directories. + * @param srcDir Source directory. + * @param destDir Destination directory. + */ + private async recursiveCopy(srcDir: string, destDir: string): Promise { + await fsPromises.mkdir(destDir, { recursive: true }); + const entries = await fsPromises.readdir(srcDir, { withFileTypes: true }); + + for (let entry of entries) { + const srcPath = path.join(srcDir, entry.name); + const destPath = path.join(destDir, entry.name); + + entry.isDirectory() ? + await this.recursiveCopy(srcPath, destPath) : + await fsPromises.copyFile(srcPath, destPath); + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default DirectoryCopier; diff --git a/dist/ts/class/DirectoryCreator.ts b/dist/ts/class/DirectoryCreator.ts new file mode 100644 index 0000000..7e6b3ea --- /dev/null +++ b/dist/ts/class/DirectoryCreator.ts @@ -0,0 +1,66 @@ +// class/DirectoryGenerator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { promises as fsPromises } from 'fs'; +import path from 'path'; + + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for creating directories. + */ + + class DirectoryCreator { + /** + * Creates directories at the specified locations asynchronously. + * @param basePath The base path where directories will be created. + * @param directories An array of directory paths to create. + * @description This method iterates over the provided array of directory paths, + * creating each directory at the specified location within the base path. + * If a directory already exists, it skips creation. This is useful for + * setting up a project structure or ensuring necessary directories are + * available before performing file operations. + * @throws Will throw an error if directory creation fails. + */ + async createDirectories(basePath: string, directories: string[]): Promise { + try { + for (const dir of directories) { + const dirPath = path.join(basePath, dir); + await fsPromises.mkdir(dirPath, { recursive: true }); + console.log(`Directory created or already exists: ${dirPath}`); + } + } catch (error) { + console.error(`Error creating directories: ${error}`); + throw error; + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default DirectoryCreator; \ No newline at end of file diff --git a/dist/ts/class/FileCopier.ts b/dist/ts/class/FileCopier.ts new file mode 100644 index 0000000..58179aa --- /dev/null +++ b/dist/ts/class/FileCopier.ts @@ -0,0 +1,63 @@ +// class/FileCopier.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for copying files from one location to another. + */ + class FileCopier { + + /** + * Copies a single file to a specified destination directory. + * @param {string} srcFile - The path of the source file to copy. + * @param {string} destDir - The destination directory where the file should be copied. + * @throws Will throw an error if the file copy operation fails. + */ + async copyFileToDirectory( + srcFile: string, + destDir: string + ): Promise { + try { + const fileName = path.basename(srcFile); + const destFilePath = path.join(destDir, fileName); + await fs.promises.copyFile(srcFile, destFilePath); + console.log(`File copied from ${srcFile} to ${destFilePath}`); + } catch (error) { + console.error('Error copying file:', error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default FileCopier; diff --git a/dist/ts/class/FileRenamer.ts b/dist/ts/class/FileRenamer.ts new file mode 100644 index 0000000..aea4669 --- /dev/null +++ b/dist/ts/class/FileRenamer.ts @@ -0,0 +1,58 @@ +// class/FileRenamer.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for renaming files. + */ + class FileRenamer { + + /** + * Renames a file from the source path to the target path. + * @param srcPath The current path of the file. + * @param targetPath The new path of the file after renaming. + * @returns Promise + */ + async renameFile(srcPath: string, targetPath: string): Promise { + try { + await fs.promises.rename(srcPath, targetPath); + console.log(`File renamed from ${srcPath} to ${targetPath}`); + } catch (error) { + console.error('Error renaming file:', error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default FileRenamer; diff --git a/dist/ts/class/FontGenerator.ts b/dist/ts/class/FontGenerator.ts new file mode 100644 index 0000000..1c45671 --- /dev/null +++ b/dist/ts/class/FontGenerator.ts @@ -0,0 +1,136 @@ +// class/FontGenerator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { generateFonts, FontAssetType, OtherAssetType } from 'fantasticon'; + + +// ============================================================================ +// Classes +// ============================================================================ + +class FontGenerator { + + async generateFonts( + sourceDirectory: string, + outputDiectory: string, + ) { + + const config = { + + + // RunnerMandatoryOptions + inputDir: sourceDirectory, // (required) + outputDir: outputDiectory, // (required) + + // RunnerOptionalOptions + name: 'icon.gl', + fontTypes: [ + FontAssetType.TTF, // TTF = "ttf" + FontAssetType.WOFF, // WOFF = "woff" + FontAssetType.WOFF2, // WOFF2 = "woff2" + FontAssetType.EOT, // EOT = "eot" + FontAssetType.SVG, // SVG = "svg" + ], + assetTypes: [ + OtherAssetType.CSS, // CSS = "css", + OtherAssetType.SCSS, // SCSS = "scss", + OtherAssetType.SASS, // SASS = "sass", + OtherAssetType.HTML, // HTML = "html", + OtherAssetType.JSON, // JSON = "json", + OtherAssetType.TS, // TS = "ts" + ], + + + + formatOptions: { + // woff: { + // // Woff Extended Metadata Block - see https://www.w3.org/TR/WOFF/#Metadata + // metadata: '...' + // }, + // ttf?: TtfOptions; // type TtfOptions = svg2ttf.FontOptions; + // svg?: SvgOptions; // type SvgOptions = Omit; + json: { indent: 4 } , + // ts: { + // // select what kind of types you want to generate + // // (default `['enum', 'constant', 'literalId', 'literalKey']`) + // types: ['enum', 'constant', 'literalId', 'literalKey'], + // // render the types with `'` instead of `"` (default is `"`) + // singleQuotes: false, + // // customise names used for the generated types and constants + // enumName: 'icon_gl', + // constantName: 'MY_CODEPOINTS' + // // literalIdName: 'IconId', + // // literalKeyName: 'IconKey' + // } + }, + pathOptions: { + json: './dist/font/icon.gl.json', + css: './dist/font/icon.gl.css', + scss: './dist/font/icon.gl.scss', + woff: './dist/font/icon.gl.woff', + woff2: './dist/font/icon.gl.woff2', + }, + // codepoints: { + // 'chevron-left': 57344, // decimal representation of 0xe000 + // 'chevron-right': 57345, + // 'thumbs-up': 57358, + // 'thumbs-down': 57359, + // }, + // fontHeight: number; + // descent: number; + // normalize: boolean; + // round: number; + selector: '.igl', + // tag: string; + // Use our custom Handlebars templates + // templates: { + // css: './build/font/icon.gl.css.hbs', + // scss: './build/font/icon.gl.scss.hbs' + // }, + prefix: 'igl', + fontsUrl: './fonts', + + // Customize generated icon IDs (unavailable with `.json` config file) + // getIconId: ({ + // basename, // `string` - Example: 'foo'; + // relativeDirPath, // `string` - Example: 'sub/dir/foo.svg' + // absoluteFilePath, // `string` - Example: '/var/icons/sub/dir/foo.svg' + // relativeFilePath, // `string` - Example: 'foo.svg' + // index // `number` - Example: `0` + // }) => [index, basename].join('_') // '0_foo' + + }; + + try { + await generateFonts(config); + console.log('Fonts generated successfully.'); + } catch (error) { + console.error('Error generating fonts:', error); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default FontGenerator; diff --git a/dist/ts/class/JavaScriptMinifier.ts b/dist/ts/class/JavaScriptMinifier.ts new file mode 100644 index 0000000..9cc485f --- /dev/null +++ b/dist/ts/class/JavaScriptMinifier.ts @@ -0,0 +1,82 @@ +// class/JavaScriptMinifier.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { minify } from 'terser'; +import { promises as fs } from 'fs'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * Class to minify JavaScript files using Terser. + */ + class JavaScriptMinifier { + + private config: any; + + /** + * Constructs an instance with the provided configuration. + * @param {any} config - Configuration object - minification options for Terser. + */ + constructor(config: any) { + this.config = config; + } + + /** + * Minifies a JavaScript file. + * @param {string} inputPath - Path to the input JavaScript file. + * @param {string} outputPath - Path to save the minified output file. + * @returns {Promise} - A promise that resolves when minification is complete. + */ + async minifyFile( + inputPath: string, + outputPath: string, + // options: object = {} + ): Promise { + + try { + // Read the input file + const inputCode = await fs.readFile(inputPath, 'utf8'); + // Minify the file using Terser + // const result = await minify(inputCode, options); + const result = await minify(inputCode, this.config); + // If minification is successful, write the output + if (result.code) { + await fs.writeFile(outputPath, result.code); + } else { + throw new Error('Minification resulted in empty output.'); + } + } catch (error) { + console.error(`Error minifying JavaScript file ${inputPath}:`, error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default JavaScriptMinifier; diff --git a/dist/ts/class/PackageCreator.ts b/dist/ts/class/PackageCreator.ts new file mode 100644 index 0000000..dead626 --- /dev/null +++ b/dist/ts/class/PackageCreator.ts @@ -0,0 +1,65 @@ +// class/PackageCreator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; +// import * as pack from '../../package.json' assert { type: 'json' }; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for creating a package.json file for a project. + */ + class PackageCreator { + + private packageJson: PackageJson; + + /** + * Initializes a new instance of the PackageCreator class. + * @param {PackageJson} packageJson - The content to be written into package.json. + */ + constructor(packageJson: PackageJson) { + this.packageJson = packageJson; + } + + /** + * Creates a package.json file in the specified directory. + * @param {string} outputDir - The directory where package.json will be created. + */ + async createPackageJson(outputDir: string): Promise { + const filePath = path.join(outputDir, 'package.json'); + const data = JSON.stringify(this.packageJson, null, 2); + + fs.writeFileSync(filePath, data, 'utf-8'); + console.log(`package.json created at ${filePath}`); + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default PackageCreator; \ No newline at end of file diff --git a/dist/ts/class/StyleProcessor.ts b/dist/ts/class/StyleProcessor.ts new file mode 100644 index 0000000..ee23fe4 --- /dev/null +++ b/dist/ts/class/StyleProcessor.ts @@ -0,0 +1,96 @@ +// class/StyleProcessor.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import * as sass from 'sass' +import postcss from 'postcss'; +import fs from 'fs'; +import postcssConfigExpanded from '../config/postcss.config.expanded.js'; +import postcssConfigCompressed from '../config/postcss.config.compressed.js'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * Class responsible for processing styles, including compiling SCSS and + * applying PostCSS transformations. + */ +class StyleProcessor { + + /** + * Processes the given CSS with PostCSS based on the provided style option. + * @param css The CSS string to process. + * @param styleOption The style option, either 'expanded' or 'compressed'. + * @returns Processed CSS string. + */ + async processPostCSS( + css: string, + styleOption: 'expanded' | 'compressed' + ) { + const config = styleOption === 'expanded' ? postcssConfigExpanded : postcssConfigCompressed; + return postcss(config.plugins).process(css, { from: undefined, map: { inline: false } }); + } + + /** + * Compiles SCSS to CSS and processes it using PostCSS. + * @param inputFile Path to the input SCSS file. + * @param outputFile Path to the output CSS file. + * @param styleOption Style option for the output. + */ + async processStyles( + inputFile: string, + outputFile: fs.PathOrFileDescriptor, + styleOption: 'expanded' | 'compressed' + ) { + try { + + // Compile SCSS to CSS + const result = await sass.compileAsync( + inputFile, { style: styleOption } + ); + + // Process the compiled CSS with PostCSS and Autoprefixer + const processed = await this.processPostCSS( + result.css, + styleOption + ); + + // Write the processed CSS to a file + fs.writeFileSync(outputFile, processed.css); + + // Write the source map file + if (processed.map) { + fs.writeFileSync(`${outputFile}.map`, processed.map.toString()); + } + } catch (err) { + // Handle errors in the compilation or processing + console.error(`Error processing styles from ${inputFile}:`, err); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default StyleProcessor; diff --git a/dist/ts/class/SvgPackager.ts b/dist/ts/class/SvgPackager.ts new file mode 100644 index 0000000..0803d29 --- /dev/null +++ b/dist/ts/class/SvgPackager.ts @@ -0,0 +1,229 @@ +// class/SvgPackager.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +// import * as fs from 'fs'; +import * as fs_extra from 'fs-extra'; +import { promises as fs } from 'fs'; +import * as glob from 'glob'; +import * as path from 'path'; +import { fileURLToPath } from "url"; +import SVGO from 'svgo'; +import { loadConfig } from 'svgo'; + +// Convert the current file's URL to a file path +const __filename = fileURLToPath(import.meta.url); + +// Derive the directory name of the current module +const __dirname = path.dirname(__filename); + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * Class for packaging SVG files. + * This class reads SVG files from a specified directory, optimizes them, + * and creates corresponding TypeScript files. + */ +class SvgPackager { + + /** + * Processes all SVG files in a given directory. + * @param directory The directory containing SVG files to process. + * @param outputDirectory The directory where optimized SVGs will be output as TypeScript files. + */ + public async processSvgFiles( + directory: string, + outputDirectory: string, + ts_output_directory: string, + json_output_directory: string, + ): Promise { + + const iconNames: string[] = []; + + try { + console.log(`Processing directory: ${directory}`); + + const svgFiles = glob.sync(`${directory}/**/*.svg`); + + for (const file of svgFiles) { + console.log(`Processing file: ${file}`); + const iconName = this.sanitizeFileName(path.basename(file, '.svg')); + iconNames.push(iconName); + console.log(`Processing icon: ${iconName}`); + const svgContent = await this.readSvgFile(file); + const optimizedSvg = await this.optimizeSvg(file, svgContent); + // svgo will always add a final newline when in pretty mode + const resultSvg = optimizedSvg.trim() + // Write the optimized SVG file + await this.writeSvgFile( + file, + iconName, + resultSvg, + outputDirectory + ); + // Write the optimized TypeScript file + await this.writeTypeScriptFile( + file, + iconName, + resultSvg, + ts_output_directory + ); + } + await this.writeIconsJson(iconNames, json_output_directory); + console.log(`Successfully processed ${svgFiles.length} SVG files.`); + } catch (error) { + console.error('Error processing SVG files:', error); + throw error; + } + } + + /** + * Reads the content of an SVG file. + * @param filePath The path to the SVG file. + * @returns The content of the SVG file. + */ + private async readSvgFile(filePath: string): Promise { + try { + const absolutePath = path.resolve(filePath); + const svgContent = await fs.readFile(absolutePath, 'utf8'); + return svgContent; + } catch (error) { + console.error('Error reading file:', filePath, error); + throw error; + } + } + + /** + * Sanitizes a file name to be a valid TypeScript identifier. + * @param fileName The original file name. + * @returns A sanitized version of the file name. + */ + private sanitizeFileName(fileName: string): string { + // Implement more robust sanitization logic if necessary + return fileName.replace(/[^a-zA-Z0-9_]/g, '_'); + } + + /** + * Optimizes SVG content using SVGO. + * @param svgContent The raw SVG content. + * @returns The optimized SVG content. + */ + private async optimizeSvg( + filePath: string, + svgContent: string + ): Promise { + + try { + + const config = await loadConfig( + path.join(__dirname, '../config/svgo.config.js') + ) + + const result = await SVGO.optimize( + svgContent, + { path: filePath, ...config } // Add SVGO options if needed + ); + + return result.data; + } catch (error) { + console.error('Error optimizing SVG:', error); + throw error; + } + } + + /** + * Creates a TypeScript file from SVG content. + * @param filePath The path of the SVG file. + * @param svgContent The optimized SVG content. + * @param outputDirectory The directory to output the TypeScript file. + */ + private async writeTypeScriptFile( + filePath: string, + iconName: string, + svgContent: string, + outputDirectory: string + ): Promise { + try { + const tsContent = `export const icon_${iconName} = \`${svgContent}\`;\n`; + const outputPath = path.join(outputDirectory, `${iconName}.ts`); + await fs_extra.outputFile(outputPath, tsContent); + } catch (error) { + console.error(`Error creating TypeScript file for ${filePath}:`, error); + throw error; + } + } + + /** + * Writes the SVG content to a file. + * @param filePath The original file path of the SVG. + * @param svgContent The SVG content to be written. + * @param outputDirectory The directory to output the SVG file. + */ + private async writeSvgFile( + filePath: string, + iconName: string, + svgContent: string, + outputDirectory: string + ): Promise { + try { + const outputPath = path.join(outputDirectory, `${iconName}.svg`); + await fs_extra.outputFile(outputPath, svgContent); + console.log(`SVG file written successfully for ${iconName}`); + } catch (error) { + console.error(`Error writing SVG file for ${iconName}:`, error); + throw error; + } + } + + /** + * Writes a JSON file containing the names of processed icons. + * This method creates a JSON file that lists all icon names which have + * been processed, making it easier to reference or index these icons in + * other parts of an application. + * + * @param iconNames An array of strings containing the names of the icons. + * @param outputDirectory The directory where the JSON file will be saved. + */ + private async writeIconsJson( + iconNames: string[], + outputDirectory: string + ): Promise { + + try { + const jsonContent = JSON.stringify(iconNames, null, 2); + const outputPath = path.join(outputDirectory, 'icons.json'); + await fs_extra.outputFile(outputPath, jsonContent); + console.log('Icons JSON file created successfully'); + } catch (error) { + console.error('Error writing icons JSON file:', error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default SvgPackager; diff --git a/dist/ts/class/SvgSpriteGenerator.ts b/dist/ts/class/SvgSpriteGenerator.ts new file mode 100644 index 0000000..4e00225 --- /dev/null +++ b/dist/ts/class/SvgSpriteGenerator.ts @@ -0,0 +1,99 @@ +// class/SvgSpriteGenerator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import svgSprite from 'svg-sprite'; +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for generating SVG sprites from individual SVG files. + */ +class SvgSpriteGenerator { + + private config: any; + + /** + * Constructs an instance of SvgSpriteGenerator with the provided configuration. + * @param {any} config - Configuration object for svg-sprite. + */ + constructor(config: any) { + this.config = config; + } + + /** + * Generates an SVG sprite from SVG files in a specified directory. + * @param {string} sourceDir - Directory containing source SVG files. + * @param {string} outputDir - Directory where the generated sprite will be saved. + */ + async generateSprite(sourceDir: string, outputDir: string) { + try { + const files = fs.readdirSync(sourceDir); + const sprite = new svgSprite(this.config); + + files.forEach(file => { + if (path.extname(file) === '.svg') { + const svgPath = path.resolve(sourceDir, file); + const content = fs.readFileSync(svgPath, 'utf8'); + sprite.add(svgPath, null, content); + } + }); + + sprite.compile((error, result) => { + if (error) { + throw error; + } + + for (const mode in result) { + for (const resource in result[mode]) { + const outputPath = path.resolve( + outputDir, + result[mode][resource].path + ); + fs.mkdirSync( + path.dirname(outputPath), + { recursive: true } + ); + fs.writeFileSync( + outputPath, + result[mode][resource].contents + ); + } + } + }); + + } catch (err) { + console.error('Error generating SVG sprite:', err); + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default SvgSpriteGenerator; diff --git a/dist/ts/class/TypeScriptCompiler.ts b/dist/ts/class/TypeScriptCompiler.ts new file mode 100644 index 0000000..8d58683 --- /dev/null +++ b/dist/ts/class/TypeScriptCompiler.ts @@ -0,0 +1,112 @@ +// class/TypeScriptCompiler.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +// import * as ts from 'typescript'; +import ts from 'typescript'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * TypeScriptCompiler class for compiling TypeScript files to JavaScript. + */ + class TypeScriptCompiler { + + private config: any; + + /** + * Constructs an instance with the provided configuration. + * @param {any} config - Configuration object + */ + constructor(config: any) { + this.config = config; + } + + /** + * Compiles TypeScript files to JavaScript. + * + * @param {string[]} filePaths - The paths of TypeScript files to be compiled. + * @param {string} outDir - The directory where the compiled JavaScript files will be saved. + * @param {ts.CompilerOptions} customOptions - Optional custom TypeScript compiler options. + * + * This method sets up a TypeScript program with given file paths and compiler options. + * It handles the compilation of TypeScript files into JavaScript, considering any provided custom options. + * Compilation errors and diagnostics are logged for debugging purposes. + * The method returns a promise that resolves when compilation is successful or rejects in case of errors. + */ + compile( + filePaths: string[], + outDir: string, + // customOptions: ts.CompilerOptions = {} + ): Promise { + return new Promise((resolve, reject) => { + + // Merge default options with custom options + const options: ts.CompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2015, + outDir, + // ...customOptions, // Merges custom compiler options + ...this.config, // Merges custom compiler options + }; + + // Create a TypeScript compiler host + const host = ts.createCompilerHost(options); + + // Create a program with the specified files and options + const program = ts.createProgram(filePaths, options, host); + + // Emit the compiled JavaScript files + const emitResult = program.emit(); + + // Check for compilation errors + const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + allDiagnostics.forEach(diagnostic => { + // Handle and print diagnostics + if (diagnostic.file) { + const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + } else { + console.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + }); + + const exitCode = emitResult.emitSkipped ? 1 : 0; + if (exitCode === 0) { + console.log('Compilation completed successfully.'); + resolve(); + } else { + console.error('Compilation failed.'); + reject(new Error('TypeScript compilation failed')); + } + }); + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default TypeScriptCompiler; diff --git a/dist/ts/class/VersionWriter.ts b/dist/ts/class/VersionWriter.ts new file mode 100644 index 0000000..9eda588 --- /dev/null +++ b/dist/ts/class/VersionWriter.ts @@ -0,0 +1,57 @@ +// class/VersionWriter.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { promises as fs } from 'fs'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for writing version information to a file. + */ + class VersionWriter { + + /** + * Writes the specified version string to a file. + * @param {string} filePath - The file path where the version will be written. + * @param {string} version - The version string to write to the file. + */ + async writeVersionToFile( + filePath: string, + version: string, + ): Promise { + try { + await fs.writeFile(filePath, version, 'utf8'); + console.log(`Version ${version} written to ${filePath}`); + } catch (error) { + console.error(`Error writing version to file: ${error}`); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default VersionWriter; diff --git a/dist/ts/config/config.ts b/dist/ts/config/config.ts new file mode 100644 index 0000000..037aee0 --- /dev/null +++ b/dist/ts/config/config.ts @@ -0,0 +1,45 @@ +// config/config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + + +export const CONFIG = { + path: { + src: './src', + dist: './dist', + + svg_input: './src/svg', + svg_output: './dist/svg', + sprite_input: './dist/svg', + sprite_output: './dist/sprite', + font_input: './dist/svg', + font_output: './dist/font', + scss_input: './src/scss', + scss_output: './dist/scss', + css_output: './dist/css', + json_output: './dist', + ts_input: './src/ts', + ts_output: './dist/ts', + ts_output_icons: './src/ts/icons', + js_output: './dist/js', + + }, + +}; \ No newline at end of file diff --git a/dist/ts/config/fantasticon.config.ts b/dist/ts/config/fantasticon.config.ts new file mode 100644 index 0000000..36dbcb7 --- /dev/null +++ b/dist/ts/config/fantasticon.config.ts @@ -0,0 +1,109 @@ +// config/fantasticon.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { generateFonts, FontAssetType, OtherAssetType } from 'fantasticon'; + + +// export const fontConfig = { + + +// // RunnerMandatoryOptions +// inputDir: sourceDirectory, // (required) +// outputDir: outputDiectory, // (required) + +// // RunnerOptionalOptions +// name: 'icon.gl', +// fontTypes: [ +// FontAssetType.TTF, // TTF = "ttf" +// FontAssetType.WOFF, // WOFF = "woff" +// FontAssetType.WOFF2, // WOFF2 = "woff2" +// FontAssetType.EOT, // EOT = "eot" +// FontAssetType.SVG, // SVG = "svg" +// ], +// assetTypes: [ +// OtherAssetType.CSS, // CSS = "css", +// OtherAssetType.SCSS, // SCSS = "scss", +// OtherAssetType.SASS, // SASS = "sass", +// OtherAssetType.HTML, // HTML = "html", +// OtherAssetType.JSON, // JSON = "json", +// OtherAssetType.TS, // TS = "ts" +// ], + + + +// formatOptions: { +// // woff: { +// // // Woff Extended Metadata Block - see https://www.w3.org/TR/WOFF/#Metadata +// // metadata: '...' +// // }, +// // ttf?: TtfOptions; // type TtfOptions = svg2ttf.FontOptions; +// // svg?: SvgOptions; // type SvgOptions = Omit; +// json: { indent: 4 } , +// // ts: { +// // // select what kind of types you want to generate +// // // (default `['enum', 'constant', 'literalId', 'literalKey']`) +// // types: ['enum', 'constant', 'literalId', 'literalKey'], +// // // render the types with `'` instead of `"` (default is `"`) +// // singleQuotes: false, +// // // customise names used for the generated types and constants +// // enumName: 'icon_gl', +// // constantName: 'MY_CODEPOINTS' +// // // literalIdName: 'IconId', +// // // literalKeyName: 'IconKey' +// // } +// }, +// pathOptions: { +// json: './dist/font/icon.gl.json', +// css: './dist/font/icon.gl.css', +// scss: './dist/font/icon.gl.scss', +// woff: './dist/font/icon.gl.woff', +// woff2: './dist/font/icon.gl.woff2', +// }, +// // codepoints: { +// // 'chevron-left': 57344, // decimal representation of 0xe000 +// // 'chevron-right': 57345, +// // 'thumbs-up': 57358, +// // 'thumbs-down': 57359, +// // }, +// // fontHeight: number; +// // descent: number; +// // normalize: boolean; +// // round: number; +// selector: '.igl', +// // tag: string; +// // Use our custom Handlebars templates +// // templates: { +// // css: './build/font/icon.gl.css.hbs', +// // scss: './build/font/icon.gl.scss.hbs' +// // }, +// prefix: 'igl', +// fontsUrl: './fonts', + +// // Customize generated icon IDs (unavailable with `.json` config file) +// // getIconId: ({ +// // basename, // `string` - Example: 'foo'; +// // relativeDirPath, // `string` - Example: 'sub/dir/foo.svg' +// // absoluteFilePath, // `string` - Example: '/var/icons/sub/dir/foo.svg' +// // relativeFilePath, // `string` - Example: 'foo.svg' +// // index // `number` - Example: `0` +// // }) => [index, basename].join('_') // '0_foo' + +// }; diff --git a/dist/ts/config/package.config.ts b/dist/ts/config/package.config.ts new file mode 100644 index 0000000..9ab3f9c --- /dev/null +++ b/dist/ts/config/package.config.ts @@ -0,0 +1,76 @@ +// config/package.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import * as pack_object from '../../../package.json' assert { type: 'json' }; + +const pack = JSON.parse(JSON.stringify(pack_object)).default; // req.body = [Object: null prototype] { title: 'product' } + + +const packageConfig = { + name: pack.name, + version: pack.version, + description: pack.description, + keywords: pack.keywords, + license: pack.license, + homepage: pack.homepage, + main: 'index.js', + files: [ + "svg/**/*.{svg}", + "js/**/*.{js,map}", + "ts/**/*.ts", + "css/**/*.{css,map}", + "scss/**/*.{scss}", + "font/**/*.{eot,otf,ttf,woff,woff2}", + "!.DS_Store" + ], + // repository: { + // type: pack.repository.type, + // url: pack.repository.url, + // }, + + // author?: string | { + // name: string; + // email?: string; + // url?: string; + // }; + // bugs?: { + // url?: string; + // email?: string; + // }; + + // contributors?: Array; + // funding?: string | { + // type: string; + // url: string; + // }; + + +} + +// ============================================================================ +// Export +// ============================================================================ + +export default packageConfig; diff --git a/dist/ts/config/postcss.config.compressed.ts b/dist/ts/config/postcss.config.compressed.ts new file mode 100644 index 0000000..151beb2 --- /dev/null +++ b/dist/ts/config/postcss.config.compressed.ts @@ -0,0 +1,47 @@ +// config/postcss.config.compressed.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import autoprefixer from 'autoprefixer'; +import cssnano from 'cssnano'; + + +// ============================================================================ +// Constants +// ============================================================================ + +const postcssConfigCompressed = { + plugins: [ + autoprefixer, + // Minification for compressed output + cssnano( + { + preset: 'default' + }, + ), + ] +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default postcssConfigCompressed; diff --git a/dist/ts/config/postcss.config.expanded.ts b/dist/ts/config/postcss.config.expanded.ts new file mode 100644 index 0000000..c4c1d3f --- /dev/null +++ b/dist/ts/config/postcss.config.expanded.ts @@ -0,0 +1,42 @@ +// config/postcss.config.expanded.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import autoprefixer from 'autoprefixer'; +import cssnano from 'cssnano'; + + +// ============================================================================ +// Constants +// ============================================================================ + +const postcssConfigExpanded = { + plugins: [ + autoprefixer, + // Include other plugins suited for the expanded output + ] +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default postcssConfigExpanded; diff --git a/dist/ts/config/svgo.config.ts b/dist/ts/config/svgo.config.ts new file mode 100644 index 0000000..436060e --- /dev/null +++ b/dist/ts/config/svgo.config.ts @@ -0,0 +1,116 @@ +// config/svgo.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import path from 'node:path' + + +// ============================================================================ +// Constants +// ============================================================================ + +const svgoConfig = { + + multipass: true, + js2svg: { + pretty: true, + indent: 2, + eol: 'lf' + }, + plugins: [ + { + name: 'preset-default', + params: { + overrides: { + removeUnknownsAndDefaults: { + // remove all `data` attributes + keepDataAttrs: false, + // keep the `role` attribute + keepRoleAttr: true, + }, + + // keep the `viewBox` attribute + removeViewBox: false, + + // customize the params of a default plugin + inlineStyles: { + onlyMatchedOnce: false, + } + } + } + }, + // The next plugins are included in svgo but are not part of preset-default, + // so we need to explicitly enable them + 'cleanupListOfValues', + { + name: 'removeAttrs', + params: { + attrs: [ + 'clip-rule', + 'fill' + ] + } + }, + // Custom plugin which resets the SVG attributes to explicit values + { + name: 'explicitAttrs', + type: 'visitor', + params: { + attributes: { + xmlns: 'http://www.w3.org/2000/svg', + width: '16', + height: '16', + fill: 'currentColor', + class: '', // We replace the class with the correct one based on filename later + viewBox: '0 0 16 16' + } + }, + fn(_root: any, params: { attributes: { [s: string]: unknown; } | ArrayLike; }, info: { path: string; }) { + if (!params.attributes) { + return null + } + const pathname = info.path + const basename = path.basename(pathname, '.svg') + + return { + element: { + enter(node: { name: string; attributes: { [x: string]: unknown; }; }, parentNode: { type: string; }) { + if (node.name === 'svg' && parentNode.type === 'root') { + // We set the `svgAttributes` in the order we want to, + // hence why we remove the attributes and add them back + node.attributes = {} + for (const [key, value] of Object.entries(params.attributes)) { + node.attributes[key] = key === 'class' ? `igl igl-${basename}` : value + } + } + } + } + } + } + } + ] +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default svgoConfig; diff --git a/dist/ts/config/svgsprite.config.ts b/dist/ts/config/svgsprite.config.ts new file mode 100644 index 0000000..c459206 --- /dev/null +++ b/dist/ts/config/svgsprite.config.ts @@ -0,0 +1,137 @@ +// config/svg-sprite.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import svgSprite from "svg-sprite"; + + +// ============================================================================ +// Constants +// ============================================================================ + +const svgspriteConfig: svgSprite.Config = { + dest: './dist/sprite', // Main output directory + // log: null, // Logging verbosity (default: no logging) + shape: { // SVG shape related options + id: { + separator: '--', // Separator for directory name traversal + generator: 'icon-%s', + // generator: function () { /*...*/ }, // SVG shape ID generator callback + pseudo: '~' // File name separator for shape states (e.g. ':hover') + }, + dimension: {// Dimension related options + maxWidth: 2000, // Max. shape width + maxHeight: 2000, // Max. shape height + precision: 2, // Floating point precision + attributes: false, // Width and height attributes on embedded shapes + }, + spacing: { // Spacing related options + padding: 0, // Padding around all shapes + box: 'content' // Padding strategy (similar to CSS `box-sizing`) + }, + transform: ['svgo'], // List of transformations / optimizations + // meta: null, // Path to YAML file with meta / accessibility data + // align: null, // Path to YAML file with extended alignment data + // dest: null // Output directory for optimized intermediate SVG shapes + }, + svg: { // General options for created SVG files + xmlDeclaration: false, // Add XML declaration to SVG sprite + // xmlDeclaration: true, // Add XML declaration to SVG sprite + doctypeDeclaration: true, // Add DOCTYPE declaration to SVG sprite + namespaceIDs: true, // Add namespace token to all IDs in SVG shapes + // namespaceIDPrefix: '', // Add a prefix to the automatically generated namespaceIDs + // namespaceClassnames: true, // Add namespace token to all CSS class names in SVG shapes + namespaceClassnames: false, // Add namespace token to all CSS class names in SVG shapes + dimensionAttributes: true // Width and height attributes on the sprite + }, + variables: {}, // Custom Mustache templating variables and functions + mode: { + css: { // CSS sprite mode + render: { + css: true // Render CSS stylesheet + } + }, + view: true, // Create a «view» sprite + defs: true, // Create a «defs» sprite + // symbol: true, // Create a «symbol» sprite + symbol: { // Create a «symbol» sprite + // dest: ".", + // inline: true, // Prepare for inline embedding + sprite: "icon.gl.svg" + }, + stack: true, // Create a «stack» sprite + // symbol: true // Symbol sprite mode + + } +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default svgspriteConfig; + + // "svgo": { + // "multipass": true, + // "plugins": [ + // { + // "name": "preset-default", + // "params": { + // "overrides": { + // "removeUnknownsAndDefaults": { + // "keepDataAttrs": false, + // "keepRoleAttr": true + // }, + // "removeViewBox": false + // } + // } + // }, + // "cleanupListOfValues", + // "removeXMLNS", + // { + // "name": "removeAttrs", + // "params": { + // "attrs": [ + // "clip-rule", + // "fill" + // ] + // } + // } + // ] + // } + + // : { + // dest: "", // Mode specific output directory + // prefix: "svg-%s", // Prefix for CSS selectors + // dimensions: "-dims", // Suffix for dimension CSS selectors + // sprite: "svg/sprite..svg", // Sprite path and name + // bust: true || false, // Cache busting (mode dependent default value) + // render: { // Stylesheet rendering definitions + // /* ------------------------------------------- + // css: false, // CSS stylesheet options + // scss: false, // Sass stylesheet options + // less: false, // LESS stylesheet options + // styl: false, // Stylus stylesheet options + // : ... // Custom stylesheet options + // ------------------------------------------- */ + // }, + // example: false // Create an HTML example document + // } \ No newline at end of file diff --git a/dist/ts/config/terser.config.ts b/dist/ts/config/terser.config.ts new file mode 100644 index 0000000..a9aacd0 --- /dev/null +++ b/dist/ts/config/terser.config.ts @@ -0,0 +1,201 @@ +// config/terser.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + + +// ============================================================================ +// Constants +// ============================================================================ + +// https://terser.org/docs/api-reference/ + +const terserConfig = { + + + parse: { + // parse options + }, + compress: { + // compress options + drop_console: true, // Remove console.log statements + drop_debugger: true, // Remove debugger statements + pure_funcs: ['console.info', 'console.debug', 'console.warn'], // Remove specific console functions + + // defaults (default: true) -- Pass false to disable most default enabled compress transforms. Useful when you only want to enable a few compress options while disabling the rest. + + // Class and object literal methods are converted will also be + // converted to arrow expressions if the resultant code is shorter: + // m(){return x} becomes m:()=>x. To do this to regular ES5 functions + // which don't use this or arguments, see unsafe_arrows. + arrows: true, // (default: true) + + // arguments (default: false) -- replace arguments[index] with function parameter name whenever possible. + + // booleans (default: true) -- various optimizations for boolean context, for example !!a ? b : c → a ? b : c + + // booleans_as_integers (default: false) -- Turn booleans into 0 and 1, also makes comparisons with booleans use == and != instead of === and !==. + + // collapse_vars (default: true) -- Collapse single-use non-constant variables, side effects permitting. + + // comparisons (default: true) -- apply certain optimizations to binary nodes, e.g. !(a <= b) → a > b (only when unsafe_comps), attempts to negate binary nodes, e.g. a = !b && !c && !d && !e → a=!(b||c||d||e) etc. Note: comparisons works best with lhs_constants enabled. + + // computed_props (default: true) -- Transforms constant computed properties into regular ones: {["computed"]: 1} is converted to {computed: 1}. + + // conditionals (default: true) -- apply optimizations for if-s and conditional expressions + + // dead_code (default: true) -- remove unreachable code + + // directives (default: true) -- remove redundant or non-standard directives + + // drop_console (default: false) -- Pass true to discard calls to console.* functions. If you only want to discard a portion of console, you can pass an array like this ['log', 'info'], which will only discard console.log、 console.info. + + // drop_debugger (default: true) -- remove debugger; statements + + // ecma (default: 5) -- Pass 2015 or greater to enable compress options that will transform ES5 code into smaller ES6+ equivalent forms. + + // evaluate (default: true) -- attempt to evaluate constant expressions + + // expression (default: false) -- Pass true to preserve completion values from terminal statements without return, e.g. in bookmarklets. + + // global_defs (default: {}) -- see conditional compilation + + // hoist_funs (default: false) -- hoist function declarations + + // hoist_props (default: true) -- hoist properties from constant object and array literals into regular variables subject to a set of constraints. For example: var o={p:1, q:2}; f(o.p, o.q); is converted to f(1, 2);. Note: hoist_props works best with mangle enabled, the compress option passes set to 2 or higher, and the compress option toplevel enabled. + + // hoist_vars (default: false) -- hoist var declarations (this is false by default because it seems to increase the size of the output in general) + + // if_return (default: true) -- optimizations for if/return and if/continue + + // inline (default: true) -- inline calls to function with simple/return statement: + + // false -- same as 0 + // 0 -- disabled inlining + // 1 -- inline simple functions + // 2 -- inline functions with arguments + // 3 -- inline functions with arguments and variables + // true -- same as 3 + // join_vars (default: true) -- join consecutive var, let and const statements + + // keep_classnames (default: false) -- Pass true to prevent the compressor from discarding class names. Pass a regular expression to only keep class names matching that regex. See also: the keep_classnames mangle option. + + // keep_fargs (default: true) -- Prevents the compressor from discarding unused function arguments. You need this for code which relies on Function.length. + + // keep_fnames (default: false) -- Pass true to prevent the compressor from discarding function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying on Function.prototype.name. See also: the keep_fnames mangle option. + + // keep_infinity (default: false) -- Pass true to prevent Infinity from being compressed into 1/0, which may cause performance issues on Chrome. + + // lhs_constants (default: true) -- Moves constant values to the left-hand side of binary nodes. foo == 42 → 42 == foo + + // loops (default: true) -- optimizations for do, while and for loops when we can statically determine the condition. + + // module (default false) -- Pass true when compressing an ES6 module. Strict mode is implied and the toplevel option as well. + + // negate_iife (default: true) -- negate "Immediately-Called Function Expressions" where the return value is discarded, to avoid the parens that the code generator would insert. + + // passes (default: 1) -- The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. + + // properties (default: true) -- rewrite property access using the dot notation, for example foo["bar"] → foo.bar + + // pure_funcs (default: null) -- You can pass an array of names and Terser will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instance var q = Math.floor(a/b). If variable q is not used elsewhere, Terser will drop it, but will still keep the Math.floor(a/b), not knowing what it does. You can pass pure_funcs: [ 'Math.floor' ] to let it know that this function won't produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower). + + // pure_getters (default: "strict") -- If you pass true for this, Terser will assume that object property access (e.g. foo.bar or foo["bar"]) doesn't have any side effects. Specify "strict" to treat foo.bar as side-effect-free only when foo is certain to not throw, i.e. not null or undefined. + + // pure_new (default: false) -- Set to true to assume new X() never has side effects. + + // reduce_vars (default: true) -- Improve optimization on variables assigned with and used as constant values. + + // reduce_funcs (default: true) -- Inline single-use functions when possible. Depends on reduce_vars being enabled. Disabling this option sometimes improves performance of the output code. + + // sequences (default: true) -- join consecutive simple statements using the comma operator. May be set to a positive integer to specify the maximum number of consecutive comma sequences that will be generated. If this option is set to true then the default sequences limit is 200. Set option to false or 0 to disable. The smallest sequences length is 2. A sequences value of 1 is grandfathered to be equivalent to true and as such means 200. On rare occasions the default sequences limit leads to very slow compress times in which case a value of 20 or less is recommended. + + // side_effects (default: true) -- Remove expressions which have no side effects and whose results aren't used. + + // switches (default: true) -- de-duplicate and remove unreachable switch branches + + // toplevel (default: false) -- drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (false by default, true to drop both unreferenced functions and variables) + + // top_retain (default: null) -- prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel) + + // typeofs (default: true) -- Transforms typeof foo == "undefined" into foo === void 0. Note: recommend to set this value to false for IE10 and earlier versions due to known issues. + + // unsafe (default: false) -- apply "unsafe" transformations (details). + + // unsafe_arrows (default: false) -- Convert ES5 style anonymous function expressions to arrow functions if the function body does not reference this. Note: it is not always safe to perform this conversion if code relies on the the function having a prototype, which arrow functions lack. This transform requires that the ecma compress option is set to 2015 or greater. + + // unsafe_comps (default: false) -- Reverse < and <= to > and >= to allow improved compression. This might be unsafe when an at least one of two operands is an object with computed values due the use of methods like get, or valueOf. This could cause change in execution order after operands in the comparison are switching. Compression only works if both comparisons and unsafe_comps are both set to true. + + // unsafe_Function (default: false) -- compress and mangle Function(args, code) when both args and code are string literals. + + // unsafe_math (default: false) -- optimize numerical expressions like 2 * x * 3 into 6 * x, which may give imprecise floating point results. + + // unsafe_symbols (default: false) -- removes keys from native Symbol declarations, e.g Symbol("kDog") becomes Symbol(). + + // unsafe_methods (default: false) -- Converts { m: function(){} } to { m(){} }. ecma must be set to 6 or greater to enable this transform. If unsafe_methods is a RegExp then key/value pairs with keys matching the RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a " is not a constructor" TypeError should any code try to new the former function. + + // unsafe_proto (default: false) -- optimize expressions like Array.prototype.slice.call(a) into [].slice.call(a) + + // unsafe_regexp (default: false) -- enable substitutions of variables with RegExp values the same way as if they are constants. + + // unsafe_undefined (default: false) -- substitute void 0 if there is a variable named undefined in scope (variable name will be mangled, typically reduced to a single character) + + // unused (default: true) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to "keep_assign") + + + }, + mangle: { + // mangle options + // Mangle names for obfuscation and size reduction + // properties: true, // Mangle property names + properties: { + // mangle property options + bare_returns: false, //support top level return statements + html5_comments: true, // (default true) + shebang: true, //(default true) -- support #!command as the first line + spidermonkey: false, // (default false) -- accept a Spidermonkey (Mozilla) AST + } + }, + format: { + // format options (can also use `output` for backwards compatibility) + comments: false, // Remove comments to reduce file size + beautify: false, // Disable beautification for smaller file size + }, + sourceMap: { + // source map options + }, + // Define ECMAScript target version + ecma: 5, // specify one of: 5, 2015, 2016, etc. + enclose: false, // or specify true, or "args:values" + keep_classnames: false, // Remove class names + keep_fnames: false, // Remove function names + ie8: false, + module: false, + nameCache: null, // or specify a name cache object + safari10: false, + toplevel: true, // Enable top-level variable and function name mangling + +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default terserConfig; diff --git a/dist/ts/config/ts.config.ts b/dist/ts/config/ts.config.ts new file mode 100644 index 0000000..c1daa82 --- /dev/null +++ b/dist/ts/config/ts.config.ts @@ -0,0 +1,139 @@ +// config/ts.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + + +// ============================================================================ +// Constants +// ============================================================================ + +const tsConfig = { + // allowImportingTsExtensions?: boolean; + // allowJs?: boolean; + // allowArbitraryExtensions?: boolean; + // allowSyntheticDefaultImports?: boolean; + // allowUmdGlobalAccess?: boolean; + // allowUnreachableCode?: boolean; + // allowUnusedLabels?: boolean; + // alwaysStrict?: boolean; + // baseUrl?: string; + // charset?: string; + // checkJs?: boolean; + // customConditions?: string[]; + // declaration?: boolean; + // declarationMap?: boolean; + // emitDeclarationOnly?: boolean; + // declarationDir?: string; + // disableSizeLimit?: boolean; + // disableSourceOfProjectReferenceRedirect?: boolean; + // disableSolutionSearching?: boolean; + // disableReferencedProjectLoad?: boolean; + // downlevelIteration?: boolean; + // emitBOM?: boolean; + // emitDecoratorMetadata?: boolean; + // exactOptionalPropertyTypes?: boolean; + // experimentalDecorators?: boolean; + // forceConsistentCasingInFileNames?: boolean; + // ignoreDeprecations?: string; + // importHelpers?: boolean; + // importsNotUsedAsValues?: ImportsNotUsedAsValues; + // inlineSourceMap?: boolean; + // inlineSources?: boolean; + // isolatedModules?: boolean; + // jsx?: JsxEmit; + // keyofStringsOnly?: boolean; + // lib?: string[]; + // locale?: string; + // mapRoot?: string; + // maxNodeModuleJsDepth?: number; + // module?: ModuleKind; + // moduleResolution?: ModuleResolutionKind; + // moduleSuffixes?: string[]; + // moduleDetection?: ModuleDetectionKind; + // newLine?: NewLineKind; + // noEmit?: boolean; + // noEmitHelpers?: boolean; + // noEmitOnError?: boolean; + // noErrorTruncation?: boolean; + // noFallthroughCasesInSwitch?: boolean; + // noImplicitAny?: boolean; + // noImplicitReturns?: boolean; + // noImplicitThis?: boolean; + // noStrictGenericChecks?: boolean; + // noUnusedLocals?: boolean; + // noUnusedParameters?: boolean; + // noImplicitUseStrict?: boolean; + // noPropertyAccessFromIndexSignature?: boolean; + // assumeChangesOnlyAffectDirectDependencies?: boolean; + // noLib?: boolean; + // noResolve?: boolean; + // noUncheckedIndexedAccess?: boolean; + // out?: string; + // outDir?: string; + // outFile: 'icon.gl.js' // string; + // paths?: MapLike; + // preserveConstEnums?: boolean; + // noImplicitOverride?: boolean; + // preserveSymlinks?: boolean; + // preserveValueImports?: boolean; + // project?: string; + // reactNamespace?: string; + // jsxFactory?: string; + // jsxFragmentFactory?: string; + // jsxImportSource?: string; + // composite?: boolean; + // incremental?: boolean; + // tsBuildInfoFile?: string; + // removeComments?: boolean; + // resolvePackageJsonExports?: boolean; + // resolvePackageJsonImports?: boolean; + // rootDir?: string; + // rootDirs?: string[]; + // skipLibCheck?: boolean; + // skipDefaultLibCheck?: boolean; + // sourceMap?: boolean; + // sourceRoot?: string; + // strict?: boolean; + // strictFunctionTypes?: boolean; + // strictBindCallApply?: boolean; + // strictNullChecks?: boolean; + // strictPropertyInitialization?: boolean; + // stripInternal?: boolean; + // suppressExcessPropertyErrors?: boolean; + // suppressImplicitAnyIndexErrors?: boolean; + // target?: ScriptTarget; + // traceResolution?: boolean; + // useUnknownInCatchVariables?: boolean; + // resolveJsonModule?: boolean; + // types?: string[]; + // /** Paths used to compute primary types search locations */ + // typeRoots?: string[]; + // verbatimModuleSyntax?: boolean; + // esModuleInterop?: boolean; + // useDefineForClassFields?: boolean; + // [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default tsConfig; diff --git a/dist/ts/index.ts b/dist/ts/index.ts new file mode 100644 index 0000000..a050a29 --- /dev/null +++ b/dist/ts/index.ts @@ -0,0 +1,70 @@ +// script/index.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + + +// Import | Utility Classes +import DirectoryCleaner from './class/DirectoryCleaner'; +import DirectoryCopier from './class/DirectoryCopier'; +import DirectoryCreator from './class/DirectoryCreator'; +import FileCopier from './class/FileCopier.js'; +import FileRenamer from './class/FileRenamer.js'; + +// Import | Internal Classes +import FontGenerator from './class/FontGenerator.js'; +import PackageCreator from './class/PackageCreator.js'; +import SvgPackager from "./class/SvgPackager.js"; +import StyleProcessor from "./class/StyleProcessor.js"; +import SvgSpriteGenerator from "./class/SvgSpriteGenerator.js"; +import VersionWriter from './class/VersionWriter.js'; +import TypeScriptCompiler from './class/TypeScriptCompiler.js'; +import JavaScriptMinifier from './class/JavaScriptMinifier.js'; + +// Import | Cconfigurations +import { CONFIG } from './config/config.js'; +import svgspriteConfig from "./config/svgsprite.config.js"; +import packageConfig from "./config/package.config.js" +import tsConfig from "./config/ts.config.js" +import tensorConfig from "./config/terser.config.js" + + +// ============================================================================ +// Export +// ============================================================================ + +export { + + // Export | Utility Classes + DirectoryCleaner, + DirectoryCopier, + DirectoryCreator, + FileCopier, + FileRenamer, + + // Export | Internal Classes + FontGenerator, + PackageCreator, + SvgPackager, + StyleProcessor, + SvgSpriteGenerator, + VersionWriter, + TypeScriptCompiler, + JavaScriptMinifier, +}; diff --git a/dist/ts/interfaces/File.ts b/dist/ts/interfaces/File.ts new file mode 100644 index 0000000..4f47dc8 --- /dev/null +++ b/dist/ts/interfaces/File.ts @@ -0,0 +1,4 @@ +interface File { + filepath: string; + source: string; +} \ No newline at end of file diff --git a/dist/ts/interfaces/PackageJson.ts b/dist/ts/interfaces/PackageJson.ts new file mode 100644 index 0000000..15078de --- /dev/null +++ b/dist/ts/interfaces/PackageJson.ts @@ -0,0 +1,70 @@ +// ============================================================================ +// Interfaces +// ============================================================================ + +interface PackageJson { + name: string; + version: string; + description?: string; + main?: string; + scripts?: Record; + dependencies?: Record; + devDependencies?: Record; + repository?: { + type: string; + url: string; + }; + keywords?: string[]; + author?: string | { + name: string; + email?: string; + url?: string; + }; + license?: string; + bugs?: { + url?: string; + email?: string; + }; + homepage?: string; + private?: boolean; + peerDependencies?: Record; + engines?: { + node?: string; + npm?: string; + }; + bin?: Record; + types?: string; + contributors?: Array; + funding?: string | { + type: string; + url: string; + }; + files?: string[]; + browserslist?: string[] | Record; + publishConfig?: Record; + config?: Record; + typings?: string; + exports?: Record; + module?: string; + sideEffects?: boolean | string[]; + + optionalDependencies?: Record; + bundledDependencies?: string[]; // or bundleDependencies + peerDependenciesMeta?: Record; + resolutions?: Record; + workspaces?: string[] | { + packages: string[]; + }; + eslintConfig?: Record; + babel?: Record; + prettier?: Record; + husky?: Record; + jest?: Record; + enginesStrict?: boolean; + os?: string[]; + cpu?: string[]; +} diff --git a/dist/ts/interfaces/SVG.ts b/dist/ts/interfaces/SVG.ts new file mode 100644 index 0000000..6067064 --- /dev/null +++ b/dist/ts/interfaces/SVG.ts @@ -0,0 +1,12 @@ + + + +// Assuming the structure of your SVG object, you might need to adjust these types +interface Svg { + metadata: { + name: string; + // ... other metadata properties + }; + source: string; + // ... other Svg properties +} \ No newline at end of file diff --git a/package.json b/package.json index 4840c43..06aca45 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "pack.gl", "description": "Package Builder.", - "version": "0.0.1", + "version": "0.0.2", "config": { "version_short": "0.0" }, @@ -31,19 +31,26 @@ "url": "https://github.com/sponsors/scape-foundation" } ], - "main": "src/scss/index.scss", + "main": "src/ts/index.ts", "type": "module", "module": "dist/js/pack.gl.js", - "style": "dist/css/pack.gl.css", - "sass": "src/scss/index.scss", "scripts": { "format": "npx prettier --write .", "lint": "eslint 'src/**/*.ts' || true", "prettify": "prettier --write 'src/**/*.ts'", - "dev": "webpack --mode development --config webpack.config.js", - "build": "webpack --mode production --config webpack.config.js", - "serve": "webpack serve --mode development --config webpack.config.js", - "start": "webpack-dev-server --mode development --config webpack.config.js" + "build": "npm run build-compile && npm run icons-process", + "build-compile2": "tsc -p tsconfig.build.json", + "build-compile": "tsc -p script/tsconfig.json", + "webpack-build": "npm run webpack-prod", + "webpack-build2": "npm run webpack-prod && npm run webpack-dev", + "webpack-dev": "webpack --mode development --config webpack.config.js", + "webpack-prod": "webpack --mode production --config webpack.config.js", + "webpack-serve": "webpack serve --mode development --config webpack.config.js", + "webpack-start": "webpack-dev-server --mode development --config webpack.config.js", + "icons-process": "node script/js/index.js", + "icons-font-min": "cleancss -O1 --format breakWith=lf --with-rebase --output font/bootstrap-icons.min.css font/bootstrap-icons.css", + "icons-compile3": "tsc filename.ts | node filename.js", + "icons-zip": "cross-env-shell \"rm -rf bootstrap-icons-$npm_package_version bootstrap-icons-$npm_package_version.zip && cp -r icons/ bootstrap-icons-$npm_package_version && cp bootstrap-icons.svg bootstrap-icons-$npm_package_version && cp -r font/ bootstrap-icons-$npm_package_version && zip -qr9 bootstrap-icons-$npm_package_version.zip bootstrap-icons-$npm_package_version && rm -rf bootstrap-icons-$npm_package_version\"" }, "devDependencies": { "@babel/core": "^7.23.6", diff --git a/script/hbs/icon.gl.css.hbs b/script/hbs/icon.gl.css.hbs new file mode 100644 index 0000000..3308cfb --- /dev/null +++ b/script/hbs/icon.gl.css.hbs @@ -0,0 +1,30 @@ +/*! + * Bootstrap Icons v1.11.2 (https://icons.getbootstrap.com/) + * Copyright 2019-2023 The Bootstrap Authors + * Licensed under MIT (https://github.com/twbs/icons/blob/main/LICENSE) + */ + +@font-face { + font-display: block; + font-family: "{{ name }}"; + src: {{{ fontSrc }}}; +} + +.{{ prefix }}::before, +[class^="{{ prefix }}-"]::before, +[class*=" {{ prefix }}-"]::before { + display: inline-block; + font-family: {{ name }} !important; + font-style: normal; + font-weight: normal !important; + font-variant: normal; + text-transform: none; + line-height: 1; + vertical-align: -.125em; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +{{# each codepoints }} +.{{ ../prefix }}-{{ @key }}::before { content: "\\{{ codepoint this }}"; } +{{/ each }} \ No newline at end of file diff --git a/script/hbs/icon.gl.html.hbs b/script/hbs/icon.gl.html.hbs new file mode 100644 index 0000000..db9db69 --- /dev/null +++ b/script/hbs/icon.gl.html.hbs @@ -0,0 +1,71 @@ + + + + + {{ name }} + + + + + + + +

{{ name }}

+ + {{# each assets }} + +
+ + <{{ ../tag }} class="{{ ../prefix }} {{ ../prefix }}-{{ @key }}"> + +
+ {{ @key }} +
+ + {{/ each }} + + + \ No newline at end of file diff --git a/script/hbs/icon.gl.sass.hbs b/script/hbs/icon.gl.sass.hbs new file mode 100644 index 0000000..7de2372 --- /dev/null +++ b/script/hbs/icon.gl.sass.hbs @@ -0,0 +1,35 @@ +${{ name }}-font: "{{ name }}" + +@font-face + font-family: ${{ name }}-font + src: {{{ fontSrc }}} + +{{# if selector }} +{{ selector }}:before +{{ else }} +{{ tag }}[class^="{{prefix}}-"]:before, {{ tag }}[class*=" {{prefix}}-"]:before +{{/ if }} + font-family: {{ name }} !important + font-style: normal + font-weight: normal !important + font-variant: normal + text-transform: none + line-height: 1 + -webkit-font-smoothing: antialiased + -moz-osx-font-smoothing: grayscale + + +${{ name }}-map: ( +{{# each codepoints }} + "{{ @key }}": "\\{{ codepoint this }}", +{{/ each }} +) + +{{# each codepoints }} +{{# if ../selector }} +{{ ../selector }}.{{ ../prefix }}-{{ @key }}:before +{{ else }} +{{ tag }}.{{ ../prefix }}-{{ @key }}:before +{{/ if }} + content: map-get(${{ ../name }}-map, "{{ @key }}") +{{/ each }} \ No newline at end of file diff --git a/script/hbs/icon.gl.scss.hbs b/script/hbs/icon.gl.scss.hbs new file mode 100644 index 0000000..62d0c2b --- /dev/null +++ b/script/hbs/icon.gl.scss.hbs @@ -0,0 +1,43 @@ +/*! + * Bootstrap Icons v1.11.2 (https://icons.getbootstrap.com/) + * Copyright 2019-2023 The Bootstrap Authors + * Licensed under MIT (https://github.com/twbs/icons/blob/main/LICENSE) + */ + +${{ name }}-font: "{{ name }}" !default; +${{ name }}-font-dir: "{{ fontsUrl }}" !default; +${{ name }}-font-file: "#{${{ name }}-font-dir}/#{${{ name }}-font}" !default; +${{ name }}-font-hash: "24e3eb84d0bcaf83d77f904c78ac1f47" !default; +${{ name }}-font-src: url("#{${{ name }}-font-file}.woff2?#{${{ name }}-font-hash}") format("woff2"), + url("#{${{ name }}-font-file}.woff?#{${{ name }}-font-hash}") format("woff") !default; + +@font-face { + font-display: block; + font-family: ${{ name }}-font; + src: ${{ name }}-font-src; +} + +.{{ prefix }}::before, +[class^="{{ prefix }}-"]::before, +[class*=" {{ prefix }}-"]::before { + display: inline-block; + font-family: ${{ name }}-font !important; + font-style: normal; + font-weight: normal !important; + font-variant: normal; + text-transform: none; + line-height: 1; + vertical-align: -.125em; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +${{ name }}-map: ( +{{# each codepoints }} + "{{ @key }}": "\\{{ codepoint this }}", +{{/ each }} +); + +@each $icon, $codepoint in ${{ name }}-map { + .{{ prefix }}-#{$icon}::before { content: $codepoint; } +} \ No newline at end of file diff --git a/script/js/class/DirCopier.js b/script/js/class/DirCopier.js new file mode 100644 index 0000000..30cc9a0 --- /dev/null +++ b/script/js/class/DirCopier.js @@ -0,0 +1,30 @@ +import { __awaiter } from "tslib"; +import fs from 'fs'; +import path from 'path'; +class DirCopier { + copyFiles(srcDir, destDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const resolvedSrcDir = path.resolve(srcDir); + const resolvedDestDir = path.resolve(destDir); + const files = fs.readdirSync(resolvedSrcDir); + console.log("FILES:", files); + files.forEach(file => { + const srcFile = path.join(resolvedSrcDir, file); + const destFile = path.join(resolvedDestDir, file); + if (fs.statSync(srcFile).isFile()) { + console.log("Copying file:", srcFile); + fs.copyFileSync(srcFile, destFile); + } + }); + console.log(`Files copied from ${resolvedSrcDir} to ${resolvedDestDir}`); + } + catch (error) { + console.error('Error copying files:', error); + throw error; + } + }); + } +} +export default DirCopier; +//# sourceMappingURL=DirCopier.js.map \ No newline at end of file diff --git a/script/js/class/DirCopier.js.map b/script/js/class/DirCopier.js.map new file mode 100644 index 0000000..f9091dc --- /dev/null +++ b/script/js/class/DirCopier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DirCopier.js","sourceRoot":"","sources":["../../ts/class/DirCopier.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAgExB,MAAM,SAAS;IAEL,SAAS,CAAC,MAAc,EAAE,OAAe;;YAC3C,IAAI,CAAC;gBACD,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBAC5C,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;gBAE9C,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;gBAC7C,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;gBAE7B,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;oBACjB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;oBAChD,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;oBAElD,IAAI,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;wBAChC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;wBACtC,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;oBACvC,CAAC;gBACL,CAAC,CAAC,CAAC;gBAEH,OAAO,CAAC,GAAG,CAAC,qBAAqB,cAAc,OAAO,eAAe,EAAE,CAAC,CAAC;YAC7E,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;CACJ;AAMD,eAAe,SAAS,CAAC"} \ No newline at end of file diff --git a/script/js/class/DirectoryCleaner.js b/script/js/class/DirectoryCleaner.js new file mode 100644 index 0000000..da46ff7 --- /dev/null +++ b/script/js/class/DirectoryCleaner.js @@ -0,0 +1,20 @@ +import fs from 'fs'; +import path from 'path'; +class DirectoryCleaner { + cleanDirectory(dirPath) { + if (fs.existsSync(dirPath)) { + fs.readdirSync(dirPath).forEach(file => { + const curPath = path.join(dirPath, file); + if (fs.lstatSync(curPath).isDirectory()) { + this.cleanDirectory(curPath); + } + else { + fs.unlinkSync(curPath); + } + }); + fs.rmdirSync(dirPath); + } + } +} +export default DirectoryCleaner; +//# sourceMappingURL=DirectoryCleaner.js.map \ No newline at end of file diff --git a/script/js/class/DirectoryCleaner.js.map b/script/js/class/DirectoryCleaner.js.map new file mode 100644 index 0000000..8b57cb7 --- /dev/null +++ b/script/js/class/DirectoryCleaner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DirectoryCleaner.js","sourceRoot":"","sources":["../../ts/class/DirectoryCleaner.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAOxB,MAAM,gBAAgB;IAMX,cAAc,CAAC,OAAe;QACjC,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YACzB,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;gBACnC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAEzC,IAAI,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;oBACtC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;gBACjC,CAAC;qBAAM,CAAC;oBACJ,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAC3B,CAAC;YACL,CAAC,CAAC,CAAC;YAEH,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC1B,CAAC;IACL,CAAC;CACJ;AAOD,eAAe,gBAAgB,CAAC"} \ No newline at end of file diff --git a/script/js/class/DirectoryCopier.js b/script/js/class/DirectoryCopier.js new file mode 100644 index 0000000..7b880a6 --- /dev/null +++ b/script/js/class/DirectoryCopier.js @@ -0,0 +1,34 @@ +import { __awaiter } from "tslib"; +import path from 'path'; +import { promises as fsPromises } from 'fs'; +class DirectoryCopier { + copyFiles(srcDir, destDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const resolvedSrcDir = path.resolve(srcDir); + const resolvedDestDir = path.resolve(destDir); + yield this.recursiveCopy(resolvedSrcDir, resolvedDestDir); + console.log(`Files copied from ${resolvedSrcDir} to ${resolvedDestDir}`); + } + catch (error) { + console.error('Error copying files:', error); + throw error; + } + }); + } + recursiveCopy(srcDir, destDir) { + return __awaiter(this, void 0, void 0, function* () { + yield fsPromises.mkdir(destDir, { recursive: true }); + const entries = yield fsPromises.readdir(srcDir, { withFileTypes: true }); + for (let entry of entries) { + const srcPath = path.join(srcDir, entry.name); + const destPath = path.join(destDir, entry.name); + entry.isDirectory() ? + yield this.recursiveCopy(srcPath, destPath) : + yield fsPromises.copyFile(srcPath, destPath); + } + }); + } +} +export default DirectoryCopier; +//# sourceMappingURL=DirectoryCopier.js.map \ No newline at end of file diff --git a/script/js/class/DirectoryCopier.js.map b/script/js/class/DirectoryCopier.js.map new file mode 100644 index 0000000..911f2e0 --- /dev/null +++ b/script/js/class/DirectoryCopier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DirectoryCopier.js","sourceRoot":"","sources":["../../ts/class/DirectoryCopier.ts"],"names":[],"mappings":";AAsBA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,IAAI,CAAC;AAU5C,MAAM,eAAe;IAQV,SAAS,CAAC,MAAc,EAAE,OAAe;;YAC5C,IAAI,CAAC;gBACD,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBAC5C,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;gBAC9C,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;gBAC1D,OAAO,CAAC,GAAG,CAAC,qBAAqB,cAAc,OAAO,eAAe,EAAE,CAAC,CAAC;YAC7E,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;IAOK,aAAa,CAAC,MAAc,EAAE,OAAe;;YAC/C,MAAM,UAAU,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACrD,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;YAE1E,KAAK,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;gBACxB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;gBAC9C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;gBAEhD,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC;oBACjB,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;oBAC7C,MAAM,UAAU,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACrD,CAAC;QACL,CAAC;KAAA;CAEJ;AAOD,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/script/js/class/DirectoryCreator.js b/script/js/class/DirectoryCreator.js new file mode 100644 index 0000000..812053b --- /dev/null +++ b/script/js/class/DirectoryCreator.js @@ -0,0 +1,21 @@ +import { __awaiter } from "tslib"; +import fs from 'fs'; +import path from 'path'; +class DirectoryCreator { + createDirectories(basePath, directories) { + return __awaiter(this, void 0, void 0, function* () { + directories.forEach(dir => { + const dirPath = path.join(basePath, dir); + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + console.log(`Directory created: ${dirPath}`); + } + else { + console.log(`Directory already exists: ${dirPath}`); + } + }); + }); + } +} +export default DirectoryCreator; +//# sourceMappingURL=DirectoryCreator.js.map \ No newline at end of file diff --git a/script/js/class/DirectoryCreator.js.map b/script/js/class/DirectoryCreator.js.map new file mode 100644 index 0000000..faa46ee --- /dev/null +++ b/script/js/class/DirectoryCreator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DirectoryCreator.js","sourceRoot":"","sources":["../../ts/class/DirectoryCreator.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAUvB,MAAM,gBAAgB;IAab,iBAAiB,CAAC,QAAgB,EAAE,WAAqB;;YAC3D,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;gBACtB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;gBACzC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;oBAC1B,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC3C,OAAO,CAAC,GAAG,CAAC,sBAAsB,OAAO,EAAE,CAAC,CAAC;gBACjD,CAAC;qBAAM,CAAC;oBACJ,OAAO,CAAC,GAAG,CAAC,6BAA6B,OAAO,EAAE,CAAC,CAAC;gBACxD,CAAC;YACL,CAAC,CAAC,CAAC;QACP,CAAC;KAAA;CACJ;AAOD,eAAe,gBAAgB,CAAC"} \ No newline at end of file diff --git a/script/js/class/FileCopier.js b/script/js/class/FileCopier.js new file mode 100644 index 0000000..8abacb1 --- /dev/null +++ b/script/js/class/FileCopier.js @@ -0,0 +1,21 @@ +import { __awaiter } from "tslib"; +import fs from 'fs'; +import path from 'path'; +class FileCopier { + copyFileToDirectory(srcFile, destDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const fileName = path.basename(srcFile); + const destFilePath = path.join(destDir, fileName); + yield fs.promises.copyFile(srcFile, destFilePath); + console.log(`File copied from ${srcFile} to ${destFilePath}`); + } + catch (error) { + console.error('Error copying file:', error); + throw error; + } + }); + } +} +export default FileCopier; +//# sourceMappingURL=FileCopier.js.map \ No newline at end of file diff --git a/script/js/class/FileCopier.js.map b/script/js/class/FileCopier.js.map new file mode 100644 index 0000000..dae10c8 --- /dev/null +++ b/script/js/class/FileCopier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileCopier.js","sourceRoot":"","sources":["../../ts/class/FileCopier.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAUvB,MAAM,UAAU;IAQP,mBAAmB,CACrB,OAAe,EACf,OAAe;;YAEf,IAAI,CAAC;gBACD,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;gBACxC,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;gBAClD,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;gBAClD,OAAO,CAAC,GAAG,CAAC,oBAAoB,OAAO,OAAO,YAAY,EAAE,CAAC,CAAC;YAClE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;gBAC5C,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;CAEJ;AAOD,eAAe,UAAU,CAAC"} \ No newline at end of file diff --git a/script/js/class/FileRenamer.js b/script/js/class/FileRenamer.js new file mode 100644 index 0000000..0a5d6fd --- /dev/null +++ b/script/js/class/FileRenamer.js @@ -0,0 +1,18 @@ +import { __awaiter } from "tslib"; +import fs from 'fs'; +class FileRenamer { + renameFile(srcPath, targetPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield fs.promises.rename(srcPath, targetPath); + console.log(`File renamed from ${srcPath} to ${targetPath}`); + } + catch (error) { + console.error('Error renaming file:', error); + throw error; + } + }); + } +} +export default FileRenamer; +//# sourceMappingURL=FileRenamer.js.map \ No newline at end of file diff --git a/script/js/class/FileRenamer.js.map b/script/js/class/FileRenamer.js.map new file mode 100644 index 0000000..60e28b4 --- /dev/null +++ b/script/js/class/FileRenamer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileRenamer.js","sourceRoot":"","sources":["../../ts/class/FileRenamer.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,MAAM,IAAI,CAAC;AAWnB,MAAM,WAAW;IAQP,UAAU,CAAC,OAAe,EAAE,UAAkB;;YACjD,IAAI,CAAC;gBACD,MAAM,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;gBAC9C,OAAO,CAAC,GAAG,CAAC,qBAAqB,OAAO,OAAO,UAAU,EAAE,CAAC,CAAC;YACjE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;CAEJ;AAOD,eAAe,WAAW,CAAC"} \ No newline at end of file diff --git a/script/js/class/FontGenerator.js b/script/js/class/FontGenerator.js new file mode 100644 index 0000000..559e50d --- /dev/null +++ b/script/js/class/FontGenerator.js @@ -0,0 +1,50 @@ +import { __awaiter } from "tslib"; +import { generateFonts, FontAssetType, OtherAssetType } from 'fantasticon'; +class FontGenerator { + generateFonts(sourceDirectory, outputDiectory) { + return __awaiter(this, void 0, void 0, function* () { + const config = { + inputDir: sourceDirectory, + outputDir: outputDiectory, + name: 'unit.gl', + fontTypes: [ + FontAssetType.TTF, + FontAssetType.WOFF, + FontAssetType.WOFF2, + FontAssetType.EOT, + FontAssetType.SVG, + ], + assetTypes: [ + OtherAssetType.CSS, + OtherAssetType.SCSS, + OtherAssetType.SASS, + OtherAssetType.HTML, + OtherAssetType.JSON, + OtherAssetType.TS, + ], + formatOptions: { + json: { indent: 4 }, + }, + pathOptions: { + json: './dist/font/unit.gl.json', + css: './dist/font/unit.gl.css', + scss: './dist/font/unit.gl.scss', + woff: './dist/font/unit.gl.woff', + woff2: './dist/font/unit.gl.woff2', + }, + selector: '.igl', + prefix: 'igl', + fontsUrl: './fonts', + }; + try { + yield generateFonts(config); + console.log('Fonts generated successfully.'); + } + catch (error) { + console.error('Error generating fonts:', error); + } + }); + } +} +export default FontGenerator; +//# sourceMappingURL=FontGenerator.js.map \ No newline at end of file diff --git a/script/js/class/FontGenerator.js.map b/script/js/class/FontGenerator.js.map new file mode 100644 index 0000000..d74cf2d --- /dev/null +++ b/script/js/class/FontGenerator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FontGenerator.js","sourceRoot":"","sources":["../../ts/class/FontGenerator.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAO3E,MAAM,aAAa;IAET,aAAa,CAAC,eAAuB,EAAE,cAAsB;;YAE/D,MAAM,MAAM,GAAG;gBAIX,QAAQ,EAAE,eAAe;gBACzB,SAAS,EAAE,cAAc;gBAGzB,IAAI,EAAE,SAAS;gBACf,SAAS,EAAE;oBACP,aAAa,CAAC,GAAG;oBACjB,aAAa,CAAC,IAAI;oBAClB,aAAa,CAAC,KAAK;oBACnB,aAAa,CAAC,GAAG;oBACjB,aAAa,CAAC,GAAG;iBACpB;gBACD,UAAU,EAAE;oBACR,cAAc,CAAC,GAAG;oBAClB,cAAc,CAAC,IAAI;oBACnB,cAAc,CAAC,IAAI;oBACnB,cAAc,CAAC,IAAI;oBACnB,cAAc,CAAC,IAAI;oBACnB,cAAc,CAAC,EAAE;iBACpB;gBAID,aAAa,EAAE;oBAOf,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE;iBAalB;gBACL,WAAW,EAAE;oBACT,IAAI,EAAI,0BAA0B;oBAClC,GAAG,EAAK,yBAAyB;oBACjC,IAAI,EAAI,0BAA0B;oBAClC,IAAI,EAAI,0BAA0B;oBAClC,KAAK,EAAG,2BAA2B;iBACtC;gBAWD,QAAQ,EAAE,MAAM;gBAOhB,MAAM,EAAE,KAAK;gBACb,QAAQ,EAAE,SAAS;aAWlB,CAAC;YAEF,IAAI,CAAC;gBACD,MAAM,aAAa,CAAC,MAAM,CAAC,CAAC;gBAC5B,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;YACjD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;YACpD,CAAC;QACL,CAAC;KAAA;CACJ;AAOD,eAAe,aAAa,CAAC"} \ No newline at end of file diff --git a/script/js/class/JavaScriptMinifier.js b/script/js/class/JavaScriptMinifier.js new file mode 100644 index 0000000..0552b73 --- /dev/null +++ b/script/js/class/JavaScriptMinifier.js @@ -0,0 +1,28 @@ +import { __awaiter } from "tslib"; +import { minify } from 'terser'; +import { promises as fs } from 'fs'; +class JavaScriptMinifier { + constructor(config) { + this.config = config; + } + minifyFile(inputPath, outputPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const inputCode = yield fs.readFile(inputPath, 'utf8'); + const result = yield minify(inputCode, this.config); + if (result.code) { + yield fs.writeFile(outputPath, result.code); + } + else { + throw new Error('Minification resulted in empty output.'); + } + } + catch (error) { + console.error(`Error minifying JavaScript file ${inputPath}:`, error); + throw error; + } + }); + } +} +export default JavaScriptMinifier; +//# sourceMappingURL=JavaScriptMinifier.js.map \ No newline at end of file diff --git a/script/js/class/JavaScriptMinifier.js.map b/script/js/class/JavaScriptMinifier.js.map new file mode 100644 index 0000000..8f54405 --- /dev/null +++ b/script/js/class/JavaScriptMinifier.js.map @@ -0,0 +1 @@ +{"version":3,"file":"JavaScriptMinifier.js","sourceRoot":"","sources":["../../ts/class/JavaScriptMinifier.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AAUnC,MAAM,kBAAkB;IAQrB,YAAY,MAAW;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAQK,UAAU,CACZ,SAAiB,EACjB,UAAkB;;YAIlB,IAAI,CAAC;gBAED,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;gBAGvD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;gBAEpD,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;oBACd,MAAM,EAAE,CAAC,SAAS,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;gBAChD,CAAC;qBAAM,CAAC;oBACJ,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;gBAC9D,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,mCAAmC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;gBACtE,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;CAEJ;AAOD,eAAe,kBAAkB,CAAC"} \ No newline at end of file diff --git a/script/js/class/ModulePackager.js b/script/js/class/ModulePackager.js new file mode 100644 index 0000000..2815e9c --- /dev/null +++ b/script/js/class/ModulePackager.js @@ -0,0 +1,41 @@ +class ModulePackager { + constructor(svgs, version) { + if (!svgs || !version) { + throw new Error("Invalid constructor arguments"); + } + this.svgs = svgs; + this.version = version; + } + getSVGContent(source) { + return source.slice(source.indexOf('>') + 1).slice(0, -6); + } + createModulePackage() { + try { + const files = this.svgs.map(svg => { + const source = this.getSVGContent(svg.source); + const json = JSON.stringify(Object.assign(Object.assign({}, svg), { source })); + return { + filepath: `${svg.metadata.name}.js`, + source: `export default ${json};` + }; + }); + files.push({ + filepath: 'package.json', + source: `{ + "name": "@acme/module-icons", + "version": "${this.version}" + }` + }); + return { + name: 'module-icons', + files + }; + } + catch (error) { + console.error('Error creating module package:', error); + throw error; + } + } +} +export default ModulePackager; +//# sourceMappingURL=ModulePackager.js.map \ No newline at end of file diff --git a/script/js/class/ModulePackager.js.map b/script/js/class/ModulePackager.js.map new file mode 100644 index 0000000..ce58b13 --- /dev/null +++ b/script/js/class/ModulePackager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ModulePackager.js","sourceRoot":"","sources":["../../ts/class/ModulePackager.ts"],"names":[],"mappings":"AA2BA,MAAM,cAAc;IAKhB,YAAY,IAAW,EAAE,OAAe;QACpC,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;IAEO,aAAa,CAAC,MAAc;QAEhC,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC9D,CAAC;IAEM,mBAAmB;QACtB,IAAI,CAAC;YACD,MAAM,KAAK,GAAW,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;gBAC1C,MAAM,MAAM,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBAC9C,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,iCAAM,GAAG,KAAE,MAAM,IAAG,CAAC;gBAEhD,OAAO;oBACH,QAAQ,EAAE,GAAG,GAAG,CAAC,QAAQ,CAAC,IAAI,KAAK;oBACnC,MAAM,EAAE,kBAAkB,IAAI,GAAG;iBACpC,CAAC;YACF,CAAC,CAAC,CAAC;YAEH,KAAK,CAAC,IAAI,CAAC;gBACP,QAAQ,EAAE,cAAc;gBACxB,MAAM,EAAE;;kCAEU,IAAI,CAAC,OAAO;kBAC5B;aACL,CAAC,CAAC;YAEH,OAAO;gBACH,IAAI,EAAE,cAAc;gBACpB,KAAK;aACR,CAAC;QACN,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAOC,eAAe,cAAc,CAAC"} \ No newline at end of file diff --git a/script/js/class/PackageCreator.js b/script/js/class/PackageCreator.js new file mode 100644 index 0000000..8c2b355 --- /dev/null +++ b/script/js/class/PackageCreator.js @@ -0,0 +1,18 @@ +import { __awaiter } from "tslib"; +import fs from 'fs'; +import path from 'path'; +class PackageCreator { + constructor(packageJson) { + this.packageJson = packageJson; + } + createPackageJson(outputDir) { + return __awaiter(this, void 0, void 0, function* () { + const filePath = path.join(outputDir, 'package.json'); + const data = JSON.stringify(this.packageJson, null, 2); + fs.writeFileSync(filePath, data, 'utf-8'); + console.log(`package.json created at ${filePath}`); + }); + } +} +export default PackageCreator; +//# sourceMappingURL=PackageCreator.js.map \ No newline at end of file diff --git a/script/js/class/PackageCreator.js.map b/script/js/class/PackageCreator.js.map new file mode 100644 index 0000000..f3101af --- /dev/null +++ b/script/js/class/PackageCreator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PackageCreator.js","sourceRoot":"","sources":["../../ts/class/PackageCreator.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAWvB,MAAM,cAAc;IAQjB,YAAY,WAAwB;QAChC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;IAMK,iBAAiB,CAAC,SAAiB;;YACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;YACtD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YAEvD,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;YAC1C,OAAO,CAAC,GAAG,CAAC,2BAA2B,QAAQ,EAAE,CAAC,CAAC;QACvD,CAAC;KAAA;CAEJ;AAOD,eAAe,cAAc,CAAC"} \ No newline at end of file diff --git a/script/js/class/StyleProcessor.js b/script/js/class/StyleProcessor.js new file mode 100644 index 0000000..ffe27de --- /dev/null +++ b/script/js/class/StyleProcessor.js @@ -0,0 +1,31 @@ +import { __awaiter } from "tslib"; +import * as sass from 'sass'; +import postcss from 'postcss'; +import fs from 'fs'; +import postcssConfigExpanded from '../config/postcss.config.expanded.js'; +import postcssConfigCompressed from '../config/postcss.config.compressed.js'; +class StyleProcessor { + processPostCSS(css, styleOption) { + return __awaiter(this, void 0, void 0, function* () { + const config = styleOption === 'expanded' ? postcssConfigExpanded : postcssConfigCompressed; + return postcss(config.plugins).process(css, { from: undefined, map: { inline: false } }); + }); + } + processStyles(inputFile, outputFile, styleOption) { + return __awaiter(this, void 0, void 0, function* () { + try { + const result = yield sass.compileAsync(inputFile, { style: styleOption }); + const processed = yield this.processPostCSS(result.css, styleOption); + fs.writeFileSync(outputFile, processed.css); + if (processed.map) { + fs.writeFileSync(`${outputFile}.map`, processed.map.toString()); + } + } + catch (err) { + console.error(`Error processing styles from ${inputFile}:`, err); + } + }); + } +} +export default StyleProcessor; +//# sourceMappingURL=StyleProcessor.js.map \ No newline at end of file diff --git a/script/js/class/StyleProcessor.js.map b/script/js/class/StyleProcessor.js.map new file mode 100644 index 0000000..143413b --- /dev/null +++ b/script/js/class/StyleProcessor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StyleProcessor.js","sourceRoot":"","sources":["../../ts/class/StyleProcessor.ts"],"names":[],"mappings":";AAqBA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAC5B,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,qBAAqB,MAAM,sCAAsC,CAAC;AACzE,OAAO,uBAAuB,MAAM,wCAAwC,CAAC;AAW7E,MAAM,cAAc;IAQV,cAAc,CAChB,GAAW,EACX,WAAsC;;YAEtC,MAAM,MAAM,GAAG,WAAW,KAAK,UAAU,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,uBAAuB,CAAC;YAC5F,OAAO,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QAC7F,CAAC;KAAA;IAQK,aAAa,CACf,SAAiB,EACjB,UAAmC,EACnC,WAAsC;;YAEtC,IAAI,CAAC;gBAGD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,YAAY,CAClC,SAAS,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,CACpC,CAAC;gBAGF,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,cAAc,CACvC,MAAM,CAAC,GAAG,EACV,WAAW,CACd,CAAC;gBAGF,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC;gBAG5C,IAAI,SAAS,CAAC,GAAG,EAAE,CAAC;oBAChB,EAAE,CAAC,aAAa,CAAC,GAAG,UAAU,MAAM,EAAE,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACpE,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBAEX,OAAO,CAAC,KAAK,CAAC,gCAAgC,SAAS,GAAG,EAAE,GAAG,CAAC,CAAC;YACrE,CAAC;QACL,CAAC;KAAA;CACJ;AAOD,eAAe,cAAc,CAAC"} \ No newline at end of file diff --git a/script/js/class/SvgPackager.js b/script/js/class/SvgPackager.js new file mode 100644 index 0000000..14f024e --- /dev/null +++ b/script/js/class/SvgPackager.js @@ -0,0 +1,109 @@ +import { __awaiter } from "tslib"; +import * as fs_extra from 'fs-extra'; +import { promises as fs } from 'fs'; +import * as glob from 'glob'; +import * as path from 'path'; +import { fileURLToPath } from "url"; +import SVGO from 'svgo'; +import { loadConfig } from 'svgo'; +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +class SvgPackager { + processSvgFiles(directory, outputDirectory, ts_output_directory, json_output_directory) { + return __awaiter(this, void 0, void 0, function* () { + const iconNames = []; + try { + console.log(`Processing directory: ${directory}`); + const svgFiles = glob.sync(`${directory}/**/*.svg`); + for (const file of svgFiles) { + console.log(`Processing file: ${file}`); + const iconName = this.sanitizeFileName(path.basename(file, '.svg')); + iconNames.push(iconName); + console.log(`Processing icon: ${iconName}`); + const svgContent = yield this.readSvgFile(file); + const optimizedSvg = yield this.optimizeSvg(file, svgContent); + const resultSvg = optimizedSvg.trim(); + yield this.writeSvgFile(file, iconName, resultSvg, outputDirectory); + yield this.writeTypeScriptFile(file, iconName, resultSvg, ts_output_directory); + } + yield this.writeIconsJson(iconNames, json_output_directory); + console.log(`Successfully processed ${svgFiles.length} SVG files.`); + } + catch (error) { + console.error('Error processing SVG files:', error); + throw error; + } + }); + } + readSvgFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const absolutePath = path.resolve(filePath); + const svgContent = yield fs.readFile(absolutePath, 'utf8'); + return svgContent; + } + catch (error) { + console.error('Error reading file:', filePath, error); + throw error; + } + }); + } + sanitizeFileName(fileName) { + return fileName.replace(/[^a-zA-Z0-9_]/g, '_'); + } + optimizeSvg(filePath, svgContent) { + return __awaiter(this, void 0, void 0, function* () { + try { + const config = yield loadConfig(path.join(__dirname, '../config/svgo.config.js')); + const result = yield SVGO.optimize(svgContent, Object.assign({ path: filePath }, config)); + return result.data; + } + catch (error) { + console.error('Error optimizing SVG:', error); + throw error; + } + }); + } + writeTypeScriptFile(filePath, iconName, svgContent, outputDirectory) { + return __awaiter(this, void 0, void 0, function* () { + try { + const tsContent = `export const icon_${iconName} = \`${svgContent}\`;\n`; + const outputPath = path.join(outputDirectory, `${iconName}.ts`); + yield fs_extra.outputFile(outputPath, tsContent); + } + catch (error) { + console.error(`Error creating TypeScript file for ${filePath}:`, error); + throw error; + } + }); + } + writeSvgFile(filePath, iconName, svgContent, outputDirectory) { + return __awaiter(this, void 0, void 0, function* () { + try { + const outputPath = path.join(outputDirectory, `${iconName}.svg`); + yield fs_extra.outputFile(outputPath, svgContent); + console.log(`SVG file written successfully for ${iconName}`); + } + catch (error) { + console.error(`Error writing SVG file for ${iconName}:`, error); + throw error; + } + }); + } + writeIconsJson(iconNames, outputDirectory) { + return __awaiter(this, void 0, void 0, function* () { + try { + const jsonContent = JSON.stringify(iconNames, null, 2); + const outputPath = path.join(outputDirectory, 'icons.json'); + yield fs_extra.outputFile(outputPath, jsonContent); + console.log('Icons JSON file created successfully'); + } + catch (error) { + console.error('Error writing icons JSON file:', error); + throw error; + } + }); + } +} +export default SvgPackager; +//# sourceMappingURL=SvgPackager.js.map \ No newline at end of file diff --git a/script/js/class/SvgPackager.js.map b/script/js/class/SvgPackager.js.map new file mode 100644 index 0000000..beb798a --- /dev/null +++ b/script/js/class/SvgPackager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SvgPackager.js","sourceRoot":"","sources":["../../ts/class/SvgPackager.ts"],"names":[],"mappings":";AAsBA,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAGlC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAGlD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAW3C,MAAM,WAAW;IAOA,eAAe,CACxB,SAAiB,EACjB,eAAuB,EACvB,mBAA2B,EAC3B,qBAA6B;;YAG7B,MAAM,SAAS,GAAa,EAAE,CAAC;YAE/B,IAAI,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,yBAAyB,SAAS,EAAE,CAAC,CAAC;gBAElD,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,SAAS,WAAW,CAAC,CAAC;gBAEpD,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;oBAC1B,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;oBACxC,MAAM,QAAQ,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;oBACpE,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;oBACzB,OAAO,CAAC,GAAG,CAAC,oBAAoB,QAAQ,EAAE,CAAC,CAAC;oBAC5C,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;oBAChD,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;oBAE9D,MAAM,SAAS,GAAG,YAAY,CAAC,IAAI,EAAE,CAAA;oBAErC,MAAM,IAAI,CAAC,YAAY,CACnB,IAAI,EACJ,QAAQ,EACR,SAAS,EACT,eAAe,CAClB,CAAC;oBAEF,MAAM,IAAI,CAAC,mBAAmB,CAC1B,IAAI,EACJ,QAAQ,EACR,SAAS,EACT,mBAAmB,CACtB,CAAC;gBACN,CAAC;gBACD,MAAM,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,qBAAqB,CAAC,CAAC;gBAC5D,OAAO,CAAC,GAAG,CAAC,0BAA0B,QAAQ,CAAC,MAAM,aAAa,CAAC,CAAC;YACxE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;gBACpD,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;IAOa,WAAW,CAAC,QAAgB;;YACtC,IAAI,CAAC;gBACD,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;gBAC5C,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;gBAC3D,OAAO,UAAU,CAAC;YACtB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACtD,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;IAOO,gBAAgB,CAAC,QAAgB;QAEjC,OAAO,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IACvD,CAAC;IAOa,WAAW,CACrB,QAAgB,EAChB,UAAkB;;YAGlB,IAAI,CAAC;gBAED,MAAM,MAAM,GAAG,MAAM,UAAU,CAC3B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,0BAA0B,CAAC,CACnD,CAAA;gBAED,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAC9B,UAAU,kBACR,IAAI,EAAE,QAAQ,IAAK,MAAM,EAC9B,CAAC;gBAEF,OAAO,MAAM,CAAC,IAAI,CAAC;YACvB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC;gBAC9C,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;IAQc,mBAAmB,CAC9B,QAAgB,EAChB,QAAgB,EAChB,UAAkB,EAClB,eAAuB;;YAEvB,IAAI,CAAC;gBACD,MAAM,SAAS,GAAG,qBAAqB,QAAQ,QAAQ,UAAU,OAAO,CAAC;gBACzE,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,QAAQ,KAAK,CAAC,CAAC;gBAChE,MAAM,QAAQ,CAAC,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,sCAAsC,QAAQ,GAAG,EAAE,KAAK,CAAC,CAAC;gBACxE,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;IAQa,YAAY,CACtB,QAAgB,EAChB,QAAgB,EAChB,UAAkB,EAClB,eAAuB;;YAEvB,IAAI,CAAC;gBACD,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,QAAQ,MAAM,CAAC,CAAC;gBACjE,MAAM,QAAQ,CAAC,UAAU,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;gBAClD,OAAO,CAAC,GAAG,CAAC,qCAAqC,QAAQ,EAAE,CAAC,CAAC;YACjE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,8BAA8B,QAAQ,GAAG,EAAE,KAAK,CAAC,CAAC;gBAChE,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;IAWa,cAAc,CACxB,SAAmB,EACnB,eAAuB;;YAGvB,IAAI,CAAC;gBACD,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;gBACvD,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;gBAC5D,MAAM,QAAQ,CAAC,UAAU,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;gBACnD,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;YACxD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;gBACvD,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC;KAAA;CAEJ;AAOD,eAAe,WAAW,CAAC"} \ No newline at end of file diff --git a/script/js/class/SvgSpriteGenerator.js b/script/js/class/SvgSpriteGenerator.js new file mode 100644 index 0000000..8df1864 --- /dev/null +++ b/script/js/class/SvgSpriteGenerator.js @@ -0,0 +1,41 @@ +import { __awaiter } from "tslib"; +import svgSprite from 'svg-sprite'; +import fs from 'fs'; +import path from 'path'; +class SvgSpriteGenerator { + constructor(config) { + this.config = config; + } + generateSprite(sourceDir, outputDir) { + return __awaiter(this, void 0, void 0, function* () { + try { + const files = fs.readdirSync(sourceDir); + const sprite = new svgSprite(this.config); + files.forEach(file => { + if (path.extname(file) === '.svg') { + const svgPath = path.resolve(sourceDir, file); + const content = fs.readFileSync(svgPath, 'utf8'); + sprite.add(svgPath, null, content); + } + }); + sprite.compile((error, result) => { + if (error) { + throw error; + } + for (const mode in result) { + for (const resource in result[mode]) { + const outputPath = path.resolve(outputDir, result[mode][resource].path); + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, result[mode][resource].contents); + } + } + }); + } + catch (err) { + console.error('Error generating SVG sprite:', err); + } + }); + } +} +export default SvgSpriteGenerator; +//# sourceMappingURL=SvgSpriteGenerator.js.map \ No newline at end of file diff --git a/script/js/class/SvgSpriteGenerator.js.map b/script/js/class/SvgSpriteGenerator.js.map new file mode 100644 index 0000000..2605453 --- /dev/null +++ b/script/js/class/SvgSpriteGenerator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SvgSpriteGenerator.js","sourceRoot":"","sources":["../../ts/class/SvgSpriteGenerator.ts"],"names":[],"mappings":";AAqBA,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAUxB,MAAM,kBAAkB;IAQpB,YAAY,MAAW;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAOK,cAAc,CAAC,SAAiB,EAAE,SAAiB;;YACrD,IAAI,CAAC;gBACD,MAAM,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;gBACxC,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAE1C,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;oBACjB,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,MAAM,EAAE,CAAC;wBAChC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;wBAC9C,MAAM,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;wBACjD,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;oBACvC,CAAC;gBACL,CAAC,CAAC,CAAC;gBAEH,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;oBAC7B,IAAI,KAAK,EAAE,CAAC;wBACR,MAAM,KAAK,CAAC;oBAChB,CAAC;oBAED,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;wBACxB,KAAK,MAAM,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;4BAClC,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAC3B,SAAS,EACT,MAAM,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,CAC9B,CAAC;4BACF,EAAE,CAAC,SAAS,CACR,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EACxB,EAAE,SAAS,EAAE,IAAI,EAAE,CACtB,CAAC;4BACF,EAAE,CAAC,aAAa,CACZ,UAAU,EACV,MAAM,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAClC,CAAC;wBACN,CAAC;oBACL,CAAC;gBACL,CAAC,CAAC,CAAC;YAEP,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACX,OAAO,CAAC,KAAK,CAAC,8BAA8B,EAAE,GAAG,CAAC,CAAC;YACvD,CAAC;QACL,CAAC;KAAA;CACJ;AAOD,eAAe,kBAAkB,CAAC"} \ No newline at end of file diff --git a/script/js/class/TypeScriptCompiler.js b/script/js/class/TypeScriptCompiler.js new file mode 100644 index 0000000..46fb616 --- /dev/null +++ b/script/js/class/TypeScriptCompiler.js @@ -0,0 +1,36 @@ +import ts from 'typescript'; +class TypeScriptCompiler { + constructor(config) { + this.config = config; + } + compile(filePaths, outDir) { + return new Promise((resolve, reject) => { + const options = Object.assign({ module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2015, outDir }, this.config); + const host = ts.createCompilerHost(options); + const program = ts.createProgram(filePaths, options, host); + const emitResult = program.emit(); + const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + allDiagnostics.forEach(diagnostic => { + if (diagnostic.file) { + const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + } + else { + console.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + }); + const exitCode = emitResult.emitSkipped ? 1 : 0; + if (exitCode === 0) { + console.log('Compilation completed successfully.'); + resolve(); + } + else { + console.error('Compilation failed.'); + reject(new Error('TypeScript compilation failed')); + } + }); + } +} +export default TypeScriptCompiler; +//# sourceMappingURL=TypeScriptCompiler.js.map \ No newline at end of file diff --git a/script/js/class/TypeScriptCompiler.js.map b/script/js/class/TypeScriptCompiler.js.map new file mode 100644 index 0000000..8e3a541 --- /dev/null +++ b/script/js/class/TypeScriptCompiler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TypeScriptCompiler.js","sourceRoot":"","sources":["../../ts/class/TypeScriptCompiler.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,YAAY,CAAC;AAU3B,MAAM,kBAAkB;IAQrB,YAAY,MAAW;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAcD,OAAO,CACH,SAAmB,EACnB,MAAc;QAGd,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAGnC,MAAM,OAAO,mBACT,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,EAC9B,MAAM,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM,EAC9B,MAAM,IAEH,IAAI,CAAC,MAAM,CACjB,CAAC;YAGF,MAAM,IAAI,GAAG,EAAE,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;YAG5C,MAAM,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;YAG3D,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;YAGlC,MAAM,cAAc,GAAG,EAAE,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;YACxF,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;gBAEhC,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC;oBAClB,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAM,CAAC,CAAC;oBAC7F,MAAM,OAAO,GAAG,EAAE,CAAC,4BAA4B,CAAC,UAAU,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;oBAC9E,OAAO,CAAC,KAAK,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC,QAAQ,KAAK,IAAI,GAAG,CAAC,IAAI,SAAS,GAAG,CAAC,MAAM,OAAO,EAAE,CAAC,CAAC;gBAC5F,CAAC;qBAAM,CAAC;oBACJ,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,4BAA4B,CAAC,UAAU,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC;gBACjF,CAAC;YACL,CAAC,CAAC,CAAC;YAEH,MAAM,QAAQ,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAChD,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;gBACjB,OAAO,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;gBACnD,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;gBACrC,MAAM,CAAC,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAOD,eAAe,kBAAkB,CAAC"} \ No newline at end of file diff --git a/script/js/class/VersionWriter.js b/script/js/class/VersionWriter.js new file mode 100644 index 0000000..90b1eb2 --- /dev/null +++ b/script/js/class/VersionWriter.js @@ -0,0 +1,17 @@ +import { __awaiter } from "tslib"; +import { promises as fs } from 'fs'; +class VersionWriter { + writeVersionToFile(filePath, version) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield fs.writeFile(filePath, version, 'utf8'); + console.log(`Version ${version} written to ${filePath}`); + } + catch (error) { + console.error(`Error writing version to file: ${error}`); + } + }); + } +} +export default VersionWriter; +//# sourceMappingURL=VersionWriter.js.map \ No newline at end of file diff --git a/script/js/class/VersionWriter.js.map b/script/js/class/VersionWriter.js.map new file mode 100644 index 0000000..e2a5270 --- /dev/null +++ b/script/js/class/VersionWriter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"VersionWriter.js","sourceRoot":"","sources":["../../ts/class/VersionWriter.ts"],"names":[],"mappings":";AAqBA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AAUnC,MAAM,aAAa;IAOV,kBAAkB,CACpB,QAAgB,EAChB,OAAe;;YAEf,IAAI,CAAC;gBACD,MAAM,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;gBAC9C,OAAO,CAAC,GAAG,CAAC,WAAW,OAAO,eAAe,QAAQ,EAAE,CAAC,CAAC;YAC7D,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,kCAAkC,KAAK,EAAE,CAAC,CAAC;YAC7D,CAAC;QACL,CAAC;KAAA;CACJ;AAOD,eAAe,aAAa,CAAC"} \ No newline at end of file diff --git a/script/js/config/config.js b/script/js/config/config.js new file mode 100644 index 0000000..7603d30 --- /dev/null +++ b/script/js/config/config.js @@ -0,0 +1,11 @@ +export const CONFIG = { + path: { + src: './src', + dist: './dist', + json_output: './dist', + ts_input: './src/ts', + ts_output: './dist/ts', + js_output: './dist/js', + }, +}; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/script/js/config/config.js.map b/script/js/config/config.js.map new file mode 100644 index 0000000..1eeb0aa --- /dev/null +++ b/script/js/config/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../ts/config/config.ts"],"names":[],"mappings":"AACA,MAAM,CAAC,MAAM,MAAM,GAAG;IAClB,IAAI,EAAE;QACF,GAAG,EAAO,OAAO;QACjB,IAAI,EAAO,QAAQ;QAEnB,WAAW,EAAS,QAAQ;QAC5B,QAAQ,EAAY,UAAU;QAC9B,SAAS,EAAW,WAAW;QAC/B,SAAS,EAAW,WAAW;KAElC;CAEJ,CAAC"} \ No newline at end of file diff --git a/script/js/config/fantasticon.config.js b/script/js/config/fantasticon.config.js new file mode 100644 index 0000000..797f36f --- /dev/null +++ b/script/js/config/fantasticon.config.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=fantasticon.config.js.map \ No newline at end of file diff --git a/script/js/config/fantasticon.config.js.map b/script/js/config/fantasticon.config.js.map new file mode 100644 index 0000000..d834499 --- /dev/null +++ b/script/js/config/fantasticon.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fantasticon.config.js","sourceRoot":"","sources":["../../ts/config/fantasticon.config.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/script/js/config/package.config.js b/script/js/config/package.config.js new file mode 100644 index 0000000..fb2d27c --- /dev/null +++ b/script/js/config/package.config.js @@ -0,0 +1,22 @@ +import * as pack_object from '../../../package.json' assert { type: 'json' }; +const pack = JSON.parse(JSON.stringify(pack_object)).default; +const packageConfig = { + name: pack.name, + version: pack.version, + description: pack.description, + keywords: pack.keywords, + license: pack.license, + homepage: pack.homepage, + main: 'index.js', + files: [ + "svg/**/*.svg", + "js/**/*.{js,map}", + "ts/**/*.ts", + "css/**/*.{css,map}", + "scss/**/*.scss", + "font/**/*.{eot,otf,ttf,woff,woff2}", + "!.DS_Store" + ], +}; +export default packageConfig; +//# sourceMappingURL=package.config.js.map \ No newline at end of file diff --git a/script/js/config/package.config.js.map b/script/js/config/package.config.js.map new file mode 100644 index 0000000..8d56d01 --- /dev/null +++ b/script/js/config/package.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"package.config.js","sourceRoot":"","sources":["../../ts/config/package.config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,WAAW,MAAM,uBAAuB,CAAC,SAAS,IAAI,EAAE,MAAM,EAAE,CAAC;AAE7E,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC;AAG7D,MAAM,aAAa,GAAG;IAClB,IAAI,EAAE,IAAI,CAAC,IAAI;IACf,OAAO,EAAE,IAAI,CAAC,OAAO;IACrB,WAAW,EAAE,IAAI,CAAC,WAAW;IAC7B,QAAQ,EAAE,IAAI,CAAC,QAAQ;IACvB,OAAO,EAAE,IAAI,CAAC,OAAO;IACrB,QAAQ,EAAE,IAAI,CAAC,QAAQ;IACvB,IAAI,EAAE,UAAU;IAChB,KAAK,EAAE;QACH,cAAc;QACd,kBAAkB;QAClB,YAAY;QACZ,oBAAoB;QACpB,gBAAgB;QAChB,oCAAoC;QACpC,YAAY;KACf;CA2BJ,CAAA;AAMD,eAAe,aAAa,CAAC"} \ No newline at end of file diff --git a/script/js/config/postcss.config.compressed.js b/script/js/config/postcss.config.compressed.js new file mode 100644 index 0000000..9f19212 --- /dev/null +++ b/script/js/config/postcss.config.compressed.js @@ -0,0 +1,12 @@ +import autoprefixer from 'autoprefixer'; +import cssnano from 'cssnano'; +const postcssConfigCompressed = { + plugins: [ + autoprefixer, + cssnano({ + preset: 'default' + }), + ] +}; +export default postcssConfigCompressed; +//# sourceMappingURL=postcss.config.compressed.js.map \ No newline at end of file diff --git a/script/js/config/postcss.config.compressed.js.map b/script/js/config/postcss.config.compressed.js.map new file mode 100644 index 0000000..b8b0de2 --- /dev/null +++ b/script/js/config/postcss.config.compressed.js.map @@ -0,0 +1 @@ +{"version":3,"file":"postcss.config.compressed.js","sourceRoot":"","sources":["../../ts/config/postcss.config.compressed.ts"],"names":[],"mappings":"AAqBA,OAAO,YAAY,MAAM,cAAc,CAAC;AACxC,OAAO,OAAO,MAAM,SAAS,CAAC;AAO9B,MAAM,uBAAuB,GAAG;IAC5B,OAAO,EAAE;QACL,YAAY;QAEZ,OAAO,CACH;YACI,MAAM,EAAE,SAAS;SACpB,CACJ;KACJ;CACJ,CAAC;AAOF,eAAe,uBAAuB,CAAC"} \ No newline at end of file diff --git a/script/js/config/postcss.config.expanded.js b/script/js/config/postcss.config.expanded.js new file mode 100644 index 0000000..4c8bf20 --- /dev/null +++ b/script/js/config/postcss.config.expanded.js @@ -0,0 +1,8 @@ +import autoprefixer from 'autoprefixer'; +const postcssConfigExpanded = { + plugins: [ + autoprefixer, + ] +}; +export default postcssConfigExpanded; +//# sourceMappingURL=postcss.config.expanded.js.map \ No newline at end of file diff --git a/script/js/config/postcss.config.expanded.js.map b/script/js/config/postcss.config.expanded.js.map new file mode 100644 index 0000000..c8316e6 --- /dev/null +++ b/script/js/config/postcss.config.expanded.js.map @@ -0,0 +1 @@ +{"version":3,"file":"postcss.config.expanded.js","sourceRoot":"","sources":["../../ts/config/postcss.config.expanded.ts"],"names":[],"mappings":"AAqBA,OAAO,YAAY,MAAM,cAAc,CAAC;AAQxC,MAAM,qBAAqB,GAAG;IAC1B,OAAO,EAAE;QACL,YAAY;KAEf;CACJ,CAAC;AAOF,eAAe,qBAAqB,CAAC"} \ No newline at end of file diff --git a/script/js/config/svgo.config.js b/script/js/config/svgo.config.js new file mode 100644 index 0000000..d5aee4f --- /dev/null +++ b/script/js/config/svgo.config.js @@ -0,0 +1,71 @@ +import path from 'node:path'; +const svgoConfig = { + multipass: true, + js2svg: { + pretty: true, + indent: 2, + eol: 'lf' + }, + plugins: [ + { + name: 'preset-default', + params: { + overrides: { + removeUnknownsAndDefaults: { + keepDataAttrs: false, + keepRoleAttr: true, + }, + removeViewBox: false, + inlineStyles: { + onlyMatchedOnce: false, + } + } + } + }, + 'cleanupListOfValues', + { + name: 'removeAttrs', + params: { + attrs: [ + 'clip-rule', + 'fill' + ] + } + }, + { + name: 'explicitAttrs', + type: 'visitor', + params: { + attributes: { + xmlns: 'http://www.w3.org/2000/svg', + width: '16', + height: '16', + fill: 'currentColor', + class: '', + viewBox: '0 0 16 16' + } + }, + fn(_root, params, info) { + if (!params.attributes) { + return null; + } + const pathname = info.path; + const basename = path.basename(pathname, '.svg'); + return { + element: { + enter(node, parentNode) { + if (node.name === 'svg' && parentNode.type === 'root') { + node.attributes = {}; + for (const [key, value] of Object.entries(params.attributes)) { + node.attributes[key] = key === 'class' ? `igl igl-${basename}` : value; + } + } + } + } + }; + } + } + ] +}; +export default svgoConfig; +//# sourceMappingURL=svgo.config.js.map \ No newline at end of file diff --git a/script/js/config/svgo.config.js.map b/script/js/config/svgo.config.js.map new file mode 100644 index 0000000..8651d5b --- /dev/null +++ b/script/js/config/svgo.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"svgo.config.js","sourceRoot":"","sources":["../../ts/config/svgo.config.ts"],"names":[],"mappings":"AAqBA,OAAO,IAAI,MAAM,WAAW,CAAA;AAO5B,MAAM,UAAU,GAAG;IACf,SAAS,EAAE,IAAI;IACf,MAAM,EAAE;QACJ,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,CAAC;QACT,GAAG,EAAE,IAAI;KACZ;IACD,OAAO,EAAE;QACL;YACI,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE;gBACJ,SAAS,EAAE;oBACP,yBAAyB,EAAE;wBAEvB,aAAa,EAAE,KAAK;wBAEpB,YAAY,EAAE,IAAI;qBACrB;oBAGD,aAAa,EAAE,KAAK;oBAGpB,YAAY,EAAE;wBACV,eAAe,EAAE,KAAK;qBACzB;iBACJ;aACJ;SACJ;QAGD,qBAAqB;QACrB;YACI,IAAI,EAAE,aAAa;YACnB,MAAM,EAAE;gBACJ,KAAK,EAAE;oBACH,WAAW;oBACX,MAAM;iBACT;aACJ;SACJ;QAED;YACI,IAAI,EAAE,eAAe;YACrB,IAAI,EAAE,SAAS;YACf,MAAM,EAAE;gBACJ,UAAU,EAAE;oBACR,KAAK,EAAE,4BAA4B;oBACnC,KAAK,EAAE,IAAI;oBACX,MAAM,EAAE,IAAI;oBACZ,IAAI,EAAE,cAAc;oBACpB,KAAK,EAAE,EAAE;oBACT,OAAO,EAAE,WAAW;iBACvB;aACJ;YACD,EAAE,CAAC,KAAU,EAAE,MAAuE,EAAE,IAAuB;gBAC3G,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;oBACrB,OAAO,IAAI,CAAA;gBACf,CAAC;gBACD,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAA;gBAC1B,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;gBAEhD,OAAO;oBACH,OAAO,EAAE;wBACL,KAAK,CAAC,IAA8D,EAAE,UAA6B;4BAC/F,IAAI,IAAI,CAAC,IAAI,KAAK,KAAK,IAAI,UAAU,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gCAGpD,IAAI,CAAC,UAAU,GAAG,EAAE,CAAA;gCACpB,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;oCAC3D,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,CAAA;gCAC1E,CAAC;4BACL,CAAC;wBACL,CAAC;qBACJ;iBACJ,CAAA;YACL,CAAC;SACJ;KACJ;CACJ,CAAC;AAOF,eAAe,UAAU,CAAC"} \ No newline at end of file diff --git a/script/js/config/svgsprite.config.js b/script/js/config/svgsprite.config.js new file mode 100644 index 0000000..65fc88b --- /dev/null +++ b/script/js/config/svgsprite.config.js @@ -0,0 +1,44 @@ +const svgspriteConfig = { + dest: './dist/sprite', + shape: { + id: { + separator: '--', + generator: 'icon-%s', + pseudo: '~' + }, + dimension: { + maxWidth: 2000, + maxHeight: 2000, + precision: 2, + attributes: false, + }, + spacing: { + padding: 0, + box: 'content' + }, + transform: ['svgo'], + }, + svg: { + xmlDeclaration: false, + doctypeDeclaration: true, + namespaceIDs: true, + namespaceClassnames: false, + dimensionAttributes: true + }, + variables: {}, + mode: { + css: { + render: { + css: true + } + }, + view: true, + defs: true, + symbol: { + sprite: "unit.gl.svg" + }, + stack: true, + } +}; +export default svgspriteConfig; +//# sourceMappingURL=svgsprite.config.js.map \ No newline at end of file diff --git a/script/js/config/svgsprite.config.js.map b/script/js/config/svgsprite.config.js.map new file mode 100644 index 0000000..2bc47f9 --- /dev/null +++ b/script/js/config/svgsprite.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"svgsprite.config.js","sourceRoot":"","sources":["../../ts/config/svgsprite.config.ts"],"names":[],"mappings":"AA4BA,MAAM,eAAe,GAAqB;IACtC,IAAI,EAAE,eAAe;IAErB,KAAK,EAAE;QACH,EAAE,EAAE;YACA,SAAS,EAAE,IAAI;YACf,SAAS,EAAE,SAAS;YAEpB,MAAM,EAAE,GAAG;SACd;QACD,SAAS,EAAE;YACP,QAAQ,EAAE,IAAI;YACd,SAAS,EAAE,IAAI;YACf,SAAS,EAAE,CAAC;YACZ,UAAU,EAAE,KAAK;SACpB;QACD,OAAO,EAAE;YACL,OAAO,EAAE,CAAC;YACV,GAAG,EAAE,SAAS;SACjB;QACD,SAAS,EAAE,CAAC,MAAM,CAAC;KAItB;IACD,GAAG,EAAE;QACD,cAAc,EAAE,KAAK;QAErB,kBAAkB,EAAE,IAAI;QACxB,YAAY,EAAE,IAAI;QAGlB,mBAAmB,EAAE,KAAK;QAC1B,mBAAmB,EAAE,IAAI;KAC5B;IACD,SAAS,EAAE,EAAE;IACb,IAAI,EAAE;QACF,GAAG,EAAE;YACD,MAAM,EAAE;gBACJ,GAAG,EAAE,IAAI;aACZ;SACJ;QACD,IAAI,EAAE,IAAI;QACV,IAAI,EAAE,IAAI;QAEV,MAAM,EAAE;YAGJ,MAAM,EAAE,aAAa;SACxB;QACD,KAAK,EAAE,IAAI;KAGd;CACJ,CAAC;AAOF,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/script/js/config/terser.config.js b/script/js/config/terser.config.js new file mode 100644 index 0000000..56e0217 --- /dev/null +++ b/script/js/config/terser.config.js @@ -0,0 +1,19 @@ +const terserCofig = { + compress: { + drop_console: true, + drop_debugger: true, + pure_funcs: ['console.info', 'console.debug', 'console.warn'], + }, + mangle: { + properties: true, + }, + format: { + comments: false, + beautify: false, + }, + keep_classnames: false, + keep_fnames: false, + toplevel: true, +}; +export default terserCofig; +//# sourceMappingURL=terser.config.js.map \ No newline at end of file diff --git a/script/js/config/terser.config.js.map b/script/js/config/terser.config.js.map new file mode 100644 index 0000000..43b9034 --- /dev/null +++ b/script/js/config/terser.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"terser.config.js","sourceRoot":"","sources":["../../ts/config/terser.config.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,GAAG;IAChB,QAAQ,EAAE;QACN,YAAY,EAAE,IAAI;QAClB,aAAa,EAAE,IAAI;QACnB,UAAU,EAAE,CAAC,cAAc,EAAE,eAAe,EAAE,cAAc,CAAC;KAChE;IACD,MAAM,EAAE;QAEJ,UAAU,EAAE,IAAI;KACnB;IACD,MAAM,EAAE;QACJ,QAAQ,EAAE,KAAK;QACf,QAAQ,EAAE,KAAK;KAClB;IACD,eAAe,EAAE,KAAK;IACtB,WAAW,EAAE,KAAK;IAClB,QAAQ,EAAE,IAAI;CACjB,CAAC;AAOF,eAAe,WAAW,CAAC"} \ No newline at end of file diff --git a/script/js/config/ts.config.js b/script/js/config/ts.config.js new file mode 100644 index 0000000..35a96a8 --- /dev/null +++ b/script/js/config/ts.config.js @@ -0,0 +1,3 @@ +const tsConfig = {}; +export default tsConfig; +//# sourceMappingURL=ts.config.js.map \ No newline at end of file diff --git a/script/js/config/ts.config.js.map b/script/js/config/ts.config.js.map new file mode 100644 index 0000000..8c43410 --- /dev/null +++ b/script/js/config/ts.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ts.config.js","sourceRoot":"","sources":["../../ts/config/ts.config.ts"],"names":[],"mappings":"AAGA,MAAM,QAAQ,GAAG,EAyGhB,CAAC;AAOF,eAAe,QAAQ,CAAC"} \ No newline at end of file diff --git a/script/js/index.js b/script/js/index.js new file mode 100644 index 0000000..06d161b --- /dev/null +++ b/script/js/index.js @@ -0,0 +1,74 @@ +import { __awaiter } from "tslib"; +import path from 'path'; +import FontGenerator from './class/FontGenerator.js'; +import SvgPackager from "./class/SvgPackager.js"; +import StyleProcessor from "./class/StyleProcessor.js"; +import SvgSpriteGenerator from "./class/SvgSpriteGenerator.js"; +import PackageCreator from './class/PackageCreator.js'; +import VersionWriter from './class/VersionWriter.js'; +import FileCopier from './class/FileCopier.js'; +import FileRenamer from './class/FileRenamer.js'; +import DirectoryCreator from './class/DirectoryCreator.js'; +import DirectoryCopier from './class/DirectoryCopier.js'; +import DirectoryCleaner from './class/DirectoryCleaner.js'; +import TypeScriptCompiler from './class/TypeScriptCompiler.js'; +import JavaScriptMinifier from './class/JavaScriptMinifier.js'; +import { CONFIG } from './config/config.js'; +import svgspriteConfig from "./config/svgsprite.config.js"; +import packageConfig from "./config/package.config.js"; +import tsConfig from "./config/ts.config.js"; +import tensorConfig from "./config/terser.config.js"; +const directories = Object.values(CONFIG.path); +const spriteGenerator = new SvgSpriteGenerator(svgspriteConfig); +const tsCompiler = new TypeScriptCompiler(tsConfig); +const jsMinifier = new JavaScriptMinifier(tensorConfig); +const packageCreator = new PackageCreator(packageConfig); +const svgPackager = new SvgPackager(); +const fontGenerator = new FontGenerator(); +const styleProcessor = new StyleProcessor(); +const versionWriter = new VersionWriter(); +const fileCopier = new FileCopier(); +const fileRenamer = new FileRenamer(); +const directoryCopier = new DirectoryCopier(); +const directoryCleaner = new DirectoryCleaner(); +const directoryCreator = new DirectoryCreator(); +function main() { + return __awaiter(this, void 0, void 0, function* () { + try { + directoryCleaner.cleanDirectory(CONFIG.path.dist); + console.log(`Directory cleaned: ${CONFIG.path.dist}`); + console.log('Starting Directory creation...'); + yield directoryCreator.createDirectories('.', directories); + try { + yield directoryCopier.recursiveCopy(CONFIG.path.ts_input, CONFIG.path.ts_output); + console.log('Files copied successfully.'); + } + catch (error) { + console.error('Error while copying files:', error); + } + yield versionWriter.writeVersionToFile('VERSION', packageConfig.version); + yield packageCreator.createPackageJson(CONFIG.path.dist); + try { + const tsFiles = [ + path.join(CONFIG.path.ts_input, 'index.ts'), + ]; + const outputDir = './dist/js'; + console.log('Starting TypeScript compilation...'); + tsCompiler.compile(tsFiles, outputDir); + console.log('TypeScript compilation completed.'); + } + catch (error) { + console.error('An error occurred:', error); + } + yield fileRenamer.renameFile(path.join(CONFIG.path.js_output, 'index.js'), path.join(CONFIG.path.js_output, 'pack.gl.js')); + yield jsMinifier.minifyFile(path.join(CONFIG.path.js_output, 'pack.gl.js'), path.join(CONFIG.path.js_output, 'pack.gl.min.js')) + .then(() => console.log('JavaScript minification completed.')) + .catch(console.error); + } + catch (error) { + console.error('An error occurred:', error); + } + }); +} +main(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/script/js/index.js.map b/script/js/index.js.map new file mode 100644 index 0000000..e01133b --- /dev/null +++ b/script/js/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../ts/index.ts"],"names":[],"mappings":";AAsBA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,aAAa,MAAM,0BAA0B,CAAC;AACrD,OAAO,WAAW,MAAM,wBAAwB,CAAC;AACjD,OAAO,cAAc,MAAM,2BAA2B,CAAC;AACvD,OAAO,kBAAkB,MAAM,+BAA+B,CAAC;AAC/D,OAAO,cAAc,MAAM,2BAA2B,CAAC;AACvD,OAAO,aAAa,MAAM,0BAA0B,CAAC;AACrD,OAAO,UAAU,MAAM,uBAAuB,CAAC;AAC/C,OAAO,WAAW,MAAM,wBAAwB,CAAC;AACjD,OAAO,gBAAgB,MAAM,6BAA6B,CAAC;AAC3D,OAAO,eAAe,MAAM,4BAA4B,CAAC;AACzD,OAAO,gBAAgB,MAAM,6BAA6B,CAAC;AAC3D,OAAO,kBAAkB,MAAM,+BAA+B,CAAC;AAC/D,OAAO,kBAAkB,MAAM,+BAA+B,CAAC;AAG/D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,eAAe,MAAM,8BAA8B,CAAC;AAC3D,OAAO,aAAa,MAAM,4BAA4B,CAAA;AACtD,OAAO,QAAQ,MAAM,uBAAuB,CAAA;AAC5C,OAAO,YAAY,MAAM,2BAA2B,CAAA;AAQpD,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,kBAAkB,CAAC,eAAe,CAAC,CAAC;AAChE,MAAM,UAAU,GAAG,IAAI,kBAAkB,CAAC,QAAQ,CAAC,CAAC;AACpD,MAAM,UAAU,GAAG,IAAI,kBAAkB,CAAC,YAAY,CAAC,CAAC;AACxD,MAAM,cAAc,GAAG,IAAI,cAAc,CAAC,aAAa,CAAC,CAAC;AACzD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AACtC,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC;AAC1C,MAAM,cAAc,GAAG,IAAI,cAAc,EAAE,CAAC;AAC5C,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC;AAC1C,MAAM,UAAU,GAAG,IAAI,UAAU,EAAE,CAAC;AACpC,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AACtC,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAC9C,MAAM,gBAAgB,GAAG,IAAI,gBAAgB,EAAE,CAAC;AAChD,MAAM,gBAAgB,GAAG,IAAI,gBAAgB,EAAE,CAAC;AAYhD,SAAe,IAAI;;QAEf,IAAI,CAAC;YAKD,gBAAgB,CAAC,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClD,OAAO,CAAC,GAAG,CAAC,sBAAsB,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAItD,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;YAE9C,MAAM,gBAAgB,CAAC,iBAAiB,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;YAM3D,IAAI,CAAC;gBACD,MAAM,eAAe,CAAC,aAAa,CAC/B,MAAM,CAAC,IAAI,CAAC,QAAQ,EACpB,MAAM,CAAC,IAAI,CAAC,SAAS,CACxB,CAAC;gBACF,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;YAC9C,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,CAAC;YACvD,CAAC;YAKD,MAAM,aAAa,CAAC,kBAAkB,CAAC,SAAS,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;YAMzE,MAAM,cAAc,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAOzD,IAAI,CAAC;gBAID,MAAM,OAAO,GAAG;oBACZ,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC;iBAI9C,CAAC;gBACF,MAAM,SAAS,GAAG,WAAW,CAAC;gBAE9B,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;gBAClD,UAAU,CAAC,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;gBACvC,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;YAGrD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC;YAC/C,CAAC;YAMD,MAAM,WAAW,CAAC,UAAU,CACxB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,EAC5C,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,CACjD,CAAA;YASD,MAAM,UAAU,CAAC,UAAU,CACvB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,EAC9C,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAGrD;iBACA,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;iBAC7D,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAK1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC;QAC/C,CAAC;IAEL,CAAC;CAAA;AAQD,IAAI,EAAE,CAAC"} \ No newline at end of file diff --git a/script/js/interfaces/File.js b/script/js/interfaces/File.js new file mode 100644 index 0000000..7da5bc0 --- /dev/null +++ b/script/js/interfaces/File.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=File.js.map \ No newline at end of file diff --git a/script/js/interfaces/File.js.map b/script/js/interfaces/File.js.map new file mode 100644 index 0000000..861a8ab --- /dev/null +++ b/script/js/interfaces/File.js.map @@ -0,0 +1 @@ +{"version":3,"file":"File.js","sourceRoot":"","sources":["../../ts/interfaces/File.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/script/js/interfaces/PackageJson.js b/script/js/interfaces/PackageJson.js new file mode 100644 index 0000000..4f3242c --- /dev/null +++ b/script/js/interfaces/PackageJson.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=PackageJson.js.map \ No newline at end of file diff --git a/script/js/interfaces/PackageJson.js.map b/script/js/interfaces/PackageJson.js.map new file mode 100644 index 0000000..8ba9bed --- /dev/null +++ b/script/js/interfaces/PackageJson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PackageJson.js","sourceRoot":"","sources":["../../ts/interfaces/PackageJson.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/script/js/interfaces/SVG.js b/script/js/interfaces/SVG.js new file mode 100644 index 0000000..e8b1633 --- /dev/null +++ b/script/js/interfaces/SVG.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=SVG.js.map \ No newline at end of file diff --git a/script/js/interfaces/SVG.js.map b/script/js/interfaces/SVG.js.map new file mode 100644 index 0000000..2bb813f --- /dev/null +++ b/script/js/interfaces/SVG.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SVG.js","sourceRoot":"","sources":["../../ts/interfaces/SVG.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/script/ts/class/DirectoryCleaner.ts b/script/ts/class/DirectoryCleaner.ts new file mode 100644 index 0000000..02580d3 --- /dev/null +++ b/script/ts/class/DirectoryCleaner.ts @@ -0,0 +1,58 @@ +// script/class/class/DirectoryCleaner.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +class DirectoryCleaner { + + /** + * Recursively deletes all contents of the directory. + * @param dirPath The path to the directory to clean. + */ + public cleanDirectory(dirPath: string): void { + if (fs.existsSync(dirPath)) { + fs.readdirSync(dirPath).forEach(file => { + const curPath = path.join(dirPath, file); + + if (fs.lstatSync(curPath).isDirectory()) { // Recurse + this.cleanDirectory(curPath); + } else { // Delete file + fs.unlinkSync(curPath); + } + }); + + fs.rmdirSync(dirPath); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default DirectoryCleaner; diff --git a/script/ts/class/DirectoryCopier.ts b/script/ts/class/DirectoryCopier.ts new file mode 100644 index 0000000..f41c87c --- /dev/null +++ b/script/ts/class/DirectoryCopier.ts @@ -0,0 +1,80 @@ +// class/DirectoryCopier.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; +import { promises as fsPromises } from 'fs'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for copying files from one directory to another. + */ +class DirectoryCopier { + + /** + * Copies all files and subdirectories from a source directory to a destination directory. + * @param srcDir The source directory path. + * @param destDir The destination directory path. + * @throws Will throw an error if copying fails for any file or directory. + */ + async copyFiles(srcDir: string, destDir: string): Promise { + try { + const resolvedSrcDir = path.resolve(srcDir); + const resolvedDestDir = path.resolve(destDir); + await this.recursiveCopy(resolvedSrcDir, resolvedDestDir); + console.log(`Files copied from ${resolvedSrcDir} to ${resolvedDestDir}`); + } catch (error) { + console.error('Error copying files:', error); + throw error; + } + } + + /** + * Recursively copies files and directories. + * @param srcDir Source directory. + * @param destDir Destination directory. + */ + async recursiveCopy(srcDir: string, destDir: string): Promise { + await fsPromises.mkdir(destDir, { recursive: true }); + const entries = await fsPromises.readdir(srcDir, { withFileTypes: true }); + + for (let entry of entries) { + const srcPath = path.join(srcDir, entry.name); + const destPath = path.join(destDir, entry.name); + + entry.isDirectory() ? + await this.recursiveCopy(srcPath, destPath) : + await fsPromises.copyFile(srcPath, destPath); + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default DirectoryCopier; diff --git a/script/ts/class/DirectoryCreator.ts b/script/ts/class/DirectoryCreator.ts new file mode 100644 index 0000000..16adcef --- /dev/null +++ b/script/ts/class/DirectoryCreator.ts @@ -0,0 +1,64 @@ +// script/class/DirectoryGenerator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for creating directories. + */ + class DirectoryCreator { + + /** + * Creates directories at the specified locations. + * @param {string} basePath - The base path where directories will be created. + * @param {string[]} directories - An array of directory paths to create. + * @description This method iterates over the provided array of directory paths, + * creating each directory at the specified location within the base path. + * If a directory already exists, it skips creation. This is useful for + * setting up a project structure or ensuring necessary directories are + * available before performing file operations. + * @throws Will throw an error if directory creation fails. + */ + async createDirectories(basePath: string, directories: string[]): Promise { + directories.forEach(dir => { + const dirPath = path.join(basePath, dir); + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + console.log(`Directory created: ${dirPath}`); + } else { + console.log(`Directory already exists: ${dirPath}`); + } + }); + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default DirectoryCreator; \ No newline at end of file diff --git a/script/ts/class/FileCopier.ts b/script/ts/class/FileCopier.ts new file mode 100644 index 0000000..42a225e --- /dev/null +++ b/script/ts/class/FileCopier.ts @@ -0,0 +1,63 @@ +// script/class/class/FileCopier.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for copying files from one location to another. + */ + class FileCopier { + + /** + * Copies a single file to a specified destination directory. + * @param {string} srcFile - The path of the source file to copy. + * @param {string} destDir - The destination directory where the file should be copied. + * @throws Will throw an error if the file copy operation fails. + */ + async copyFileToDirectory( + srcFile: string, + destDir: string + ): Promise { + try { + const fileName = path.basename(srcFile); + const destFilePath = path.join(destDir, fileName); + await fs.promises.copyFile(srcFile, destFilePath); + console.log(`File copied from ${srcFile} to ${destFilePath}`); + } catch (error) { + console.error('Error copying file:', error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default FileCopier; diff --git a/script/ts/class/FileRenamer.ts b/script/ts/class/FileRenamer.ts new file mode 100644 index 0000000..49dc0cd --- /dev/null +++ b/script/ts/class/FileRenamer.ts @@ -0,0 +1,58 @@ +// script/class/class/FileRenamer.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for renaming files. + */ + class FileRenamer { + + /** + * Renames a file from the source path to the target path. + * @param srcPath The current path of the file. + * @param targetPath The new path of the file after renaming. + * @returns Promise + */ + async renameFile(srcPath: string, targetPath: string): Promise { + try { + await fs.promises.rename(srcPath, targetPath); + console.log(`File renamed from ${srcPath} to ${targetPath}`); + } catch (error) { + console.error('Error renaming file:', error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default FileRenamer; diff --git a/script/ts/class/FontGenerator.ts b/script/ts/class/FontGenerator.ts new file mode 100644 index 0000000..77924ed --- /dev/null +++ b/script/ts/class/FontGenerator.ts @@ -0,0 +1,133 @@ +// script/class/FontGenerator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { generateFonts, FontAssetType, OtherAssetType } from 'fantasticon'; + + +// ============================================================================ +// Classes +// ============================================================================ + +class FontGenerator { + + async generateFonts(sourceDirectory: string, outputDiectory: string) { + + const config = { + + + // RunnerMandatoryOptions + inputDir: sourceDirectory, // (required) + outputDir: outputDiectory, // (required) + + // RunnerOptionalOptions + name: 'unit.gl', + fontTypes: [ + FontAssetType.TTF, // TTF = "ttf" + FontAssetType.WOFF, // WOFF = "woff" + FontAssetType.WOFF2, // WOFF2 = "woff2" + FontAssetType.EOT, // EOT = "eot" + FontAssetType.SVG, // SVG = "svg" + ], + assetTypes: [ + OtherAssetType.CSS, // CSS = "css", + OtherAssetType.SCSS, // SCSS = "scss", + OtherAssetType.SASS, // SASS = "sass", + OtherAssetType.HTML, // HTML = "html", + OtherAssetType.JSON, // JSON = "json", + OtherAssetType.TS, // TS = "ts" + ], + + + + formatOptions: { + // woff: { + // // Woff Extended Metadata Block - see https://www.w3.org/TR/WOFF/#Metadata + // metadata: '...' + // }, + // ttf?: TtfOptions; // type TtfOptions = svg2ttf.FontOptions; + // svg?: SvgOptions; // type SvgOptions = Omit; + json: { indent: 4 } , + // ts: { + // // select what kind of types you want to generate + // // (default `['enum', 'constant', 'literalId', 'literalKey']`) + // types: ['enum', 'constant', 'literalId', 'literalKey'], + // // render the types with `'` instead of `"` (default is `"`) + // singleQuotes: false, + // // customise names used for the generated types and constants + // enumName: 'icon_gl', + // constantName: 'MY_CODEPOINTS' + // // literalIdName: 'IconId', + // // literalKeyName: 'IconKey' + // } + }, + pathOptions: { + json: './dist/font/unit.gl.json', + css: './dist/font/unit.gl.css', + scss: './dist/font/unit.gl.scss', + woff: './dist/font/unit.gl.woff', + woff2: './dist/font/unit.gl.woff2', + }, + // codepoints: { + // 'chevron-left': 57344, // decimal representation of 0xe000 + // 'chevron-right': 57345, + // 'thumbs-up': 57358, + // 'thumbs-down': 57359, + // }, + // fontHeight: number; + // descent: number; + // normalize: boolean; + // round: number; + selector: '.igl', + // tag: string; + // Use our custom Handlebars templates + // templates: { + // css: './build/font/unit.gl.css.hbs', + // scss: './build/font/unit.gl.scss.hbs' + // }, + prefix: 'igl', + fontsUrl: './fonts', + + // Customize generated icon IDs (unavailable with `.json` config file) + // getIconId: ({ + // basename, // `string` - Example: 'foo'; + // relativeDirPath, // `string` - Example: 'sub/dir/foo.svg' + // absoluteFilePath, // `string` - Example: '/var/icons/sub/dir/foo.svg' + // relativeFilePath, // `string` - Example: 'foo.svg' + // index // `number` - Example: `0` + // }) => [index, basename].join('_') // '0_foo' + + }; + + try { + await generateFonts(config); + console.log('Fonts generated successfully.'); + } catch (error) { + console.error('Error generating fonts:', error); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default FontGenerator; diff --git a/script/ts/class/JavaScriptMinifier.ts b/script/ts/class/JavaScriptMinifier.ts new file mode 100644 index 0000000..0d69ca2 --- /dev/null +++ b/script/ts/class/JavaScriptMinifier.ts @@ -0,0 +1,82 @@ +// script/class/class/JavaScriptMinifier.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { minify } from 'terser'; +import { promises as fs } from 'fs'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * Class to minify JavaScript files using Terser. + */ + class JavaScriptMinifier { + + private config: any; + + /** + * Constructs an instance with the provided configuration. + * @param {any} config - Configuration object - minification options for Terser. + */ + constructor(config: any) { + this.config = config; + } + + /** + * Minifies a JavaScript file. + * @param {string} inputPath - Path to the input JavaScript file. + * @param {string} outputPath - Path to save the minified output file. + * @returns {Promise} - A promise that resolves when minification is complete. + */ + async minifyFile( + inputPath: string, + outputPath: string, + // options: object = {} + ): Promise { + + try { + // Read the input file + const inputCode = await fs.readFile(inputPath, 'utf8'); + // Minify the file using Terser + // const result = await minify(inputCode, options); + const result = await minify(inputCode, this.config); + // If minification is successful, write the output + if (result.code) { + await fs.writeFile(outputPath, result.code); + } else { + throw new Error('Minification resulted in empty output.'); + } + } catch (error) { + console.error(`Error minifying JavaScript file ${inputPath}:`, error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default JavaScriptMinifier; diff --git a/script/ts/class/PackageCreator.ts b/script/ts/class/PackageCreator.ts new file mode 100644 index 0000000..4d8be17 --- /dev/null +++ b/script/ts/class/PackageCreator.ts @@ -0,0 +1,65 @@ +// script/class/PackageCreator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import fs from 'fs'; +import path from 'path'; +// import * as pack from '../../package.json' assert { type: 'json' }; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for creating a package.json file for a project. + */ + class PackageCreator { + + private packageJson: PackageJson; + + /** + * Initializes a new instance of the PackageCreator class. + * @param {PackageJson} packageJson - The content to be written into package.json. + */ + constructor(packageJson: PackageJson) { + this.packageJson = packageJson; + } + + /** + * Creates a package.json file in the specified directory. + * @param {string} outputDir - The directory where package.json will be created. + */ + async createPackageJson(outputDir: string): Promise { + const filePath = path.join(outputDir, 'package.json'); + const data = JSON.stringify(this.packageJson, null, 2); + + fs.writeFileSync(filePath, data, 'utf-8'); + console.log(`package.json created at ${filePath}`); + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default PackageCreator; \ No newline at end of file diff --git a/script/ts/class/StyleProcessor.ts b/script/ts/class/StyleProcessor.ts new file mode 100644 index 0000000..eda0779 --- /dev/null +++ b/script/ts/class/StyleProcessor.ts @@ -0,0 +1,96 @@ +// script/class/StyleProcessor.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import * as sass from 'sass' +import postcss from 'postcss'; +import fs from 'fs'; +import postcssConfigExpanded from '../config/postcss.config.expanded.js'; +import postcssConfigCompressed from '../config/postcss.config.compressed.js'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * Class responsible for processing styles, including compiling SCSS and + * applying PostCSS transformations. + */ +class StyleProcessor { + + /** + * Processes the given CSS with PostCSS based on the provided style option. + * @param css The CSS string to process. + * @param styleOption The style option, either 'expanded' or 'compressed'. + * @returns Processed CSS string. + */ + async processPostCSS( + css: string, + styleOption: 'expanded' | 'compressed' + ) { + const config = styleOption === 'expanded' ? postcssConfigExpanded : postcssConfigCompressed; + return postcss(config.plugins).process(css, { from: undefined, map: { inline: false } }); + } + + /** + * Compiles SCSS to CSS and processes it using PostCSS. + * @param inputFile Path to the input SCSS file. + * @param outputFile Path to the output CSS file. + * @param styleOption Style option for the output. + */ + async processStyles( + inputFile: string, + outputFile: fs.PathOrFileDescriptor, + styleOption: 'expanded' | 'compressed' + ) { + try { + + // Compile SCSS to CSS + const result = await sass.compileAsync( + inputFile, { style: styleOption } + ); + + // Process the compiled CSS with PostCSS and Autoprefixer + const processed = await this.processPostCSS( + result.css, + styleOption + ); + + // Write the processed CSS to a file + fs.writeFileSync(outputFile, processed.css); + + // Write the source map file + if (processed.map) { + fs.writeFileSync(`${outputFile}.map`, processed.map.toString()); + } + } catch (err) { + // Handle errors in the compilation or processing + console.error(`Error processing styles from ${inputFile}:`, err); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default StyleProcessor; diff --git a/script/ts/class/SvgPackager.ts b/script/ts/class/SvgPackager.ts new file mode 100644 index 0000000..95e6e15 --- /dev/null +++ b/script/ts/class/SvgPackager.ts @@ -0,0 +1,229 @@ +// script/class/SvgPackager.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +// import * as fs from 'fs'; +import * as fs_extra from 'fs-extra'; +import { promises as fs } from 'fs'; // Using promisified fs +import * as glob from 'glob'; +import * as path from 'path'; +import { fileURLToPath } from "url"; +import SVGO from 'svgo'; +import { loadConfig } from 'svgo'; + +// Convert the current file's URL to a file path +const __filename = fileURLToPath(import.meta.url); + +// Derive the directory name of the current module +const __dirname = path.dirname(__filename); + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * Class for packaging SVG files. + * This class reads SVG files from a specified directory, optimizes them, + * and creates corresponding TypeScript files. + */ +class SvgPackager { + + /** + * Processes all SVG files in a given directory. + * @param directory The directory containing SVG files to process. + * @param outputDirectory The directory where optimized SVGs will be output as TypeScript files. + */ + public async processSvgFiles( + directory: string, + outputDirectory: string, + ts_output_directory: string, + json_output_directory: string, + ): Promise { + + const iconNames: string[] = []; + + try { + console.log(`Processing directory: ${directory}`); + + const svgFiles = glob.sync(`${directory}/**/*.svg`); + + for (const file of svgFiles) { + console.log(`Processing file: ${file}`); + const iconName = this.sanitizeFileName(path.basename(file, '.svg')); + iconNames.push(iconName); + console.log(`Processing icon: ${iconName}`); + const svgContent = await this.readSvgFile(file); + const optimizedSvg = await this.optimizeSvg(file, svgContent); + // svgo will always add a final newline when in pretty mode + const resultSvg = optimizedSvg.trim() + // Write the optimized SVG file + await this.writeSvgFile( + file, + iconName, + resultSvg, + outputDirectory + ); + // Write the optimized TypeScript file + await this.writeTypeScriptFile( + file, + iconName, + resultSvg, + ts_output_directory + ); + } + await this.writeIconsJson(iconNames, json_output_directory); + console.log(`Successfully processed ${svgFiles.length} SVG files.`); + } catch (error) { + console.error('Error processing SVG files:', error); + throw error; + } + } + + /** + * Reads the content of an SVG file. + * @param filePath The path to the SVG file. + * @returns The content of the SVG file. + */ + private async readSvgFile(filePath: string): Promise { + try { + const absolutePath = path.resolve(filePath); + const svgContent = await fs.readFile(absolutePath, 'utf8'); + return svgContent; + } catch (error) { + console.error('Error reading file:', filePath, error); + throw error; + } + } + + /** + * Sanitizes a file name to be a valid TypeScript identifier. + * @param fileName The original file name. + * @returns A sanitized version of the file name. + */ + private sanitizeFileName(fileName: string): string { + // Implement more robust sanitization logic if necessary + return fileName.replace(/[^a-zA-Z0-9_]/g, '_'); + } + + /** + * Optimizes SVG content using SVGO. + * @param svgContent The raw SVG content. + * @returns The optimized SVG content. + */ + private async optimizeSvg( + filePath: string, + svgContent: string + ): Promise { + + try { + + const config = await loadConfig( + path.join(__dirname, '../config/svgo.config.js') + ) + + const result = await SVGO.optimize( + svgContent, + { path: filePath, ...config } // Add SVGO options if needed + ); + + return result.data; + } catch (error) { + console.error('Error optimizing SVG:', error); + throw error; + } + } + + /** + * Creates a TypeScript file from SVG content. + * @param filePath The path of the SVG file. + * @param svgContent The optimized SVG content. + * @param outputDirectory The directory to output the TypeScript file. + */ + private async writeTypeScriptFile( + filePath: string, + iconName: string, + svgContent: string, + outputDirectory: string + ): Promise { + try { + const tsContent = `export const icon_${iconName} = \`${svgContent}\`;\n`; + const outputPath = path.join(outputDirectory, `${iconName}.ts`); + await fs_extra.outputFile(outputPath, tsContent); + } catch (error) { + console.error(`Error creating TypeScript file for ${filePath}:`, error); + throw error; + } + } + + /** + * Writes the SVG content to a file. + * @param filePath The original file path of the SVG. + * @param svgContent The SVG content to be written. + * @param outputDirectory The directory to output the SVG file. + */ + private async writeSvgFile( + filePath: string, + iconName: string, + svgContent: string, + outputDirectory: string + ): Promise { + try { + const outputPath = path.join(outputDirectory, `${iconName}.svg`); + await fs_extra.outputFile(outputPath, svgContent); + console.log(`SVG file written successfully for ${iconName}`); + } catch (error) { + console.error(`Error writing SVG file for ${iconName}:`, error); + throw error; + } + } + + /** + * Writes a JSON file containing the names of processed icons. + * This method creates a JSON file that lists all icon names which have + * been processed, making it easier to reference or index these icons in + * other parts of an application. + * + * @param iconNames An array of strings containing the names of the icons. + * @param outputDirectory The directory where the JSON file will be saved. + */ + private async writeIconsJson( + iconNames: string[], + outputDirectory: string + ): Promise { + + try { + const jsonContent = JSON.stringify(iconNames, null, 2); + const outputPath = path.join(outputDirectory, 'icons.json'); + await fs_extra.outputFile(outputPath, jsonContent); + console.log('Icons JSON file created successfully'); + } catch (error) { + console.error('Error writing icons JSON file:', error); + throw error; + } + } + +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default SvgPackager; diff --git a/script/ts/class/SvgSpriteGenerator.ts b/script/ts/class/SvgSpriteGenerator.ts new file mode 100644 index 0000000..2646237 --- /dev/null +++ b/script/ts/class/SvgSpriteGenerator.ts @@ -0,0 +1,98 @@ +// script/class/SvgSpriteGenerator.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import svgSprite from 'svg-sprite'; +import fs from 'fs'; +import path from 'path'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for generating SVG sprites from individual SVG files. + */ +class SvgSpriteGenerator { + + private config: any; + + /** + * Constructs an instance of SvgSpriteGenerator with the provided configuration. + * @param {any} config - Configuration object for svg-sprite. + */ + constructor(config: any) { + this.config = config; + } + + /** + * Generates an SVG sprite from SVG files in a specified directory. + * @param {string} sourceDir - Directory containing source SVG files. + * @param {string} outputDir - Directory where the generated sprite will be saved. + */ + async generateSprite(sourceDir: string, outputDir: string) { + try { + const files = fs.readdirSync(sourceDir); + const sprite = new svgSprite(this.config); + + files.forEach(file => { + if (path.extname(file) === '.svg') { + const svgPath = path.resolve(sourceDir, file); + const content = fs.readFileSync(svgPath, 'utf8'); + sprite.add(svgPath, null, content); + } + }); + + sprite.compile((error, result) => { + if (error) { + throw error; + } + + for (const mode in result) { + for (const resource in result[mode]) { + const outputPath = path.resolve( + outputDir, + result[mode][resource].path + ); + fs.mkdirSync( + path.dirname(outputPath), + { recursive: true } + ); + fs.writeFileSync( + outputPath, + result[mode][resource].contents + ); + } + } + }); + + } catch (err) { + console.error('Error generating SVG sprite:', err); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default SvgSpriteGenerator; diff --git a/script/ts/class/TypeScriptCompiler.ts b/script/ts/class/TypeScriptCompiler.ts new file mode 100644 index 0000000..a422b2e --- /dev/null +++ b/script/ts/class/TypeScriptCompiler.ts @@ -0,0 +1,112 @@ +// script/class/TypeScriptCompiler.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +// import * as ts from 'typescript'; +import ts from 'typescript'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * TypeScriptCompiler class for compiling TypeScript files to JavaScript. + */ + class TypeScriptCompiler { + + private config: any; + + /** + * Constructs an instance with the provided configuration. + * @param {any} config - Configuration object + */ + constructor(config: any) { + this.config = config; + } + + /** + * Compiles TypeScript files to JavaScript. + * + * @param {string[]} filePaths - The paths of TypeScript files to be compiled. + * @param {string} outDir - The directory where the compiled JavaScript files will be saved. + * @param {ts.CompilerOptions} customOptions - Optional custom TypeScript compiler options. + * + * This method sets up a TypeScript program with given file paths and compiler options. + * It handles the compilation of TypeScript files into JavaScript, considering any provided custom options. + * Compilation errors and diagnostics are logged for debugging purposes. + * The method returns a promise that resolves when compilation is successful or rejects in case of errors. + */ + compile( + filePaths: string[], + outDir: string, + // customOptions: ts.CompilerOptions = {} + ): Promise { + return new Promise((resolve, reject) => { + + // Merge default options with custom options + const options: ts.CompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2015, + outDir, + // ...customOptions, // Merges custom compiler options + ...this.config, // Merges custom compiler options + }; + + // Create a TypeScript compiler host + const host = ts.createCompilerHost(options); + + // Create a program with the specified files and options + const program = ts.createProgram(filePaths, options, host); + + // Emit the compiled JavaScript files + const emitResult = program.emit(); + + // Check for compilation errors + const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + allDiagnostics.forEach(diagnostic => { + // Handle and print diagnostics + if (diagnostic.file) { + const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + } else { + console.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + } + }); + + const exitCode = emitResult.emitSkipped ? 1 : 0; + if (exitCode === 0) { + console.log('Compilation completed successfully.'); + resolve(); + } else { + console.error('Compilation failed.'); + reject(new Error('TypeScript compilation failed')); + } + }); + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default TypeScriptCompiler; diff --git a/script/ts/class/VersionWriter.ts b/script/ts/class/VersionWriter.ts new file mode 100644 index 0000000..db11320 --- /dev/null +++ b/script/ts/class/VersionWriter.ts @@ -0,0 +1,57 @@ +// script/class/VersionWriter.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import { promises as fs } from 'fs'; + + +// ============================================================================ +// Classes +// ============================================================================ + +/** + * A class for writing version information to a file. + */ + class VersionWriter { + + /** + * Writes the specified version string to a file. + * @param {string} filePath - The file path where the version will be written. + * @param {string} version - The version string to write to the file. + */ + async writeVersionToFile( + filePath: string, + version: string, + ): Promise { + try { + await fs.writeFile(filePath, version, 'utf8'); + console.log(`Version ${version} written to ${filePath}`); + } catch (error) { + console.error(`Error writing version to file: ${error}`); + } + } +} + + +// ============================================================================ +// Export +// ============================================================================ + +export default VersionWriter; diff --git a/script/ts/config/config.ts b/script/ts/config/config.ts new file mode 100644 index 0000000..1a7c930 --- /dev/null +++ b/script/ts/config/config.ts @@ -0,0 +1,14 @@ + +export const CONFIG = { + path: { + src: './src', + dist: './dist', + + json_output: './dist', + ts_input: './src/ts', + ts_output: './dist/ts', + js_output: './dist/js', + + }, + +}; \ No newline at end of file diff --git a/script/ts/config/fantasticon.config.ts b/script/ts/config/fantasticon.config.ts new file mode 100644 index 0000000..27c9f9c --- /dev/null +++ b/script/ts/config/fantasticon.config.ts @@ -0,0 +1,88 @@ +import { generateFonts, FontAssetType, OtherAssetType } from 'fantasticon'; + + +// export const fontConfig = { + + +// // RunnerMandatoryOptions +// inputDir: sourceDirectory, // (required) +// outputDir: outputDiectory, // (required) + +// // RunnerOptionalOptions +// name: 'unit.gl', +// fontTypes: [ +// FontAssetType.TTF, // TTF = "ttf" +// FontAssetType.WOFF, // WOFF = "woff" +// FontAssetType.WOFF2, // WOFF2 = "woff2" +// FontAssetType.EOT, // EOT = "eot" +// FontAssetType.SVG, // SVG = "svg" +// ], +// assetTypes: [ +// OtherAssetType.CSS, // CSS = "css", +// OtherAssetType.SCSS, // SCSS = "scss", +// OtherAssetType.SASS, // SASS = "sass", +// OtherAssetType.HTML, // HTML = "html", +// OtherAssetType.JSON, // JSON = "json", +// OtherAssetType.TS, // TS = "ts" +// ], + + + +// formatOptions: { +// // woff: { +// // // Woff Extended Metadata Block - see https://www.w3.org/TR/WOFF/#Metadata +// // metadata: '...' +// // }, +// // ttf?: TtfOptions; // type TtfOptions = svg2ttf.FontOptions; +// // svg?: SvgOptions; // type SvgOptions = Omit; +// json: { indent: 4 } , +// // ts: { +// // // select what kind of types you want to generate +// // // (default `['enum', 'constant', 'literalId', 'literalKey']`) +// // types: ['enum', 'constant', 'literalId', 'literalKey'], +// // // render the types with `'` instead of `"` (default is `"`) +// // singleQuotes: false, +// // // customise names used for the generated types and constants +// // enumName: 'icon_gl', +// // constantName: 'MY_CODEPOINTS' +// // // literalIdName: 'IconId', +// // // literalKeyName: 'IconKey' +// // } +// }, +// pathOptions: { +// json: './dist/font/unit.gl.json', +// css: './dist/font/unit.gl.css', +// scss: './dist/font/unit.gl.scss', +// woff: './dist/font/unit.gl.woff', +// woff2: './dist/font/unit.gl.woff2', +// }, +// // codepoints: { +// // 'chevron-left': 57344, // decimal representation of 0xe000 +// // 'chevron-right': 57345, +// // 'thumbs-up': 57358, +// // 'thumbs-down': 57359, +// // }, +// // fontHeight: number; +// // descent: number; +// // normalize: boolean; +// // round: number; +// selector: '.igl', +// // tag: string; +// // Use our custom Handlebars templates +// // templates: { +// // css: './build/font/unit.gl.css.hbs', +// // scss: './build/font/unit.gl.scss.hbs' +// // }, +// prefix: 'igl', +// fontsUrl: './fonts', + +// // Customize generated icon IDs (unavailable with `.json` config file) +// // getIconId: ({ +// // basename, // `string` - Example: 'foo'; +// // relativeDirPath, // `string` - Example: 'sub/dir/foo.svg' +// // absoluteFilePath, // `string` - Example: '/var/icons/sub/dir/foo.svg' +// // relativeFilePath, // `string` - Example: 'foo.svg' +// // index // `number` - Example: `0` +// // }) => [index, basename].join('_') // '0_foo' + +// }; diff --git a/script/ts/config/package.config.ts b/script/ts/config/package.config.ts new file mode 100644 index 0000000..4796928 --- /dev/null +++ b/script/ts/config/package.config.ts @@ -0,0 +1,55 @@ +import * as pack_object from '../../../package.json' assert { type: 'json' }; + +const pack = JSON.parse(JSON.stringify(pack_object)).default; // req.body = [Object: null prototype] { title: 'product' } + + +const packageConfig = { + name: pack.name, + version: pack.version, + description: pack.description, + keywords: pack.keywords, + license: pack.license, + homepage: pack.homepage, + main: 'index.js', + files: [ + "svg/**/*.svg", + "js/**/*.{js,map}", + "ts/**/*.ts", + "css/**/*.{css,map}", + "scss/**/*.scss", + "font/**/*.{eot,otf,ttf,woff,woff2}", + "!.DS_Store" + ], + // repository: { + // type: pack.repository.type, + // url: pack.repository.url, + // }, + + // author?: string | { + // name: string; + // email?: string; + // url?: string; + // }; + // bugs?: { + // url?: string; + // email?: string; + // }; + + // contributors?: Array; + // funding?: string | { + // type: string; + // url: string; + // }; + + +} + +// ============================================================================ +// Export +// ============================================================================ + +export default packageConfig; diff --git a/script/ts/config/postcss.config.compressed.ts b/script/ts/config/postcss.config.compressed.ts new file mode 100644 index 0000000..b151bc6 --- /dev/null +++ b/script/ts/config/postcss.config.compressed.ts @@ -0,0 +1,47 @@ +// script/config/postcss.config.compressed.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import autoprefixer from 'autoprefixer'; +import cssnano from 'cssnano'; + + +// ============================================================================ +// Constants +// ============================================================================ + +const postcssConfigCompressed = { + plugins: [ + autoprefixer, + // Minification for compressed output + cssnano( + { + preset: 'default' + }, + ), + ] +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default postcssConfigCompressed; diff --git a/script/ts/config/postcss.config.expanded.ts b/script/ts/config/postcss.config.expanded.ts new file mode 100644 index 0000000..ff82010 --- /dev/null +++ b/script/ts/config/postcss.config.expanded.ts @@ -0,0 +1,42 @@ +// script/config/postcss.config.expanded.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import autoprefixer from 'autoprefixer'; +import cssnano from 'cssnano'; + + +// ============================================================================ +// Constants +// ============================================================================ + +const postcssConfigExpanded = { + plugins: [ + autoprefixer, + // Include other plugins suited for the expanded output + ] +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default postcssConfigExpanded; diff --git a/script/ts/config/svgo.config.ts b/script/ts/config/svgo.config.ts new file mode 100644 index 0000000..eb14ed5 --- /dev/null +++ b/script/ts/config/svgo.config.ts @@ -0,0 +1,115 @@ +// script/config/svgo.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import path from 'node:path' + + +// ============================================================================ +// Constants +// ============================================================================ + +const svgoConfig = { + multipass: true, + js2svg: { + pretty: true, + indent: 2, + eol: 'lf' + }, + plugins: [ + { + name: 'preset-default', + params: { + overrides: { + removeUnknownsAndDefaults: { + // remove all `data` attributes + keepDataAttrs: false, + // keep the `role` attribute + keepRoleAttr: true, + }, + + // keep the `viewBox` attribute + removeViewBox: false, + + // customize the params of a default plugin + inlineStyles: { + onlyMatchedOnce: false, + } + } + } + }, + // The next plugins are included in svgo but are not part of preset-default, + // so we need to explicitly enable them + 'cleanupListOfValues', + { + name: 'removeAttrs', + params: { + attrs: [ + 'clip-rule', + 'fill' + ] + } + }, + // Custom plugin which resets the SVG attributes to explicit values + { + name: 'explicitAttrs', + type: 'visitor', + params: { + attributes: { + xmlns: 'http://www.w3.org/2000/svg', + width: '16', + height: '16', + fill: 'currentColor', + class: '', // We replace the class with the correct one based on filename later + viewBox: '0 0 16 16' + } + }, + fn(_root: any, params: { attributes: { [s: string]: unknown; } | ArrayLike; }, info: { path: string; }) { + if (!params.attributes) { + return null + } + const pathname = info.path + const basename = path.basename(pathname, '.svg') + + return { + element: { + enter(node: { name: string; attributes: { [x: string]: unknown; }; }, parentNode: { type: string; }) { + if (node.name === 'svg' && parentNode.type === 'root') { + // We set the `svgAttributes` in the order we want to, + // hence why we remove the attributes and add them back + node.attributes = {} + for (const [key, value] of Object.entries(params.attributes)) { + node.attributes[key] = key === 'class' ? `igl igl-${basename}` : value + } + } + } + } + } + } + } + ] +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default svgoConfig; diff --git a/script/ts/config/svgsprite.config.ts b/script/ts/config/svgsprite.config.ts new file mode 100644 index 0000000..879593d --- /dev/null +++ b/script/ts/config/svgsprite.config.ts @@ -0,0 +1,137 @@ +// script/config/svg-sprite.config.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +import svgSprite from "svg-sprite"; + + +// ============================================================================ +// Constants +// ============================================================================ + +const svgspriteConfig: svgSprite.Config = { + dest: './dist/sprite', // Main output directory + // log: null, // Logging verbosity (default: no logging) + shape: { // SVG shape related options + id: { + separator: '--', // Separator for directory name traversal + generator: 'icon-%s', + // generator: function () { /*...*/ }, // SVG shape ID generator callback + pseudo: '~' // File name separator for shape states (e.g. ':hover') + }, + dimension: {// Dimension related options + maxWidth: 2000, // Max. shape width + maxHeight: 2000, // Max. shape height + precision: 2, // Floating point precision + attributes: false, // Width and height attributes on embedded shapes + }, + spacing: { // Spacing related options + padding: 0, // Padding around all shapes + box: 'content' // Padding strategy (similar to CSS `box-sizing`) + }, + transform: ['svgo'], // List of transformations / optimizations + // meta: null, // Path to YAML file with meta / accessibility data + // align: null, // Path to YAML file with extended alignment data + // dest: null // Output directory for optimized intermediate SVG shapes + }, + svg: { // General options for created SVG files + xmlDeclaration: false, // Add XML declaration to SVG sprite + // xmlDeclaration: true, // Add XML declaration to SVG sprite + doctypeDeclaration: true, // Add DOCTYPE declaration to SVG sprite + namespaceIDs: true, // Add namespace token to all IDs in SVG shapes + // namespaceIDPrefix: '', // Add a prefix to the automatically generated namespaceIDs + // namespaceClassnames: true, // Add namespace token to all CSS class names in SVG shapes + namespaceClassnames: false, // Add namespace token to all CSS class names in SVG shapes + dimensionAttributes: true // Width and height attributes on the sprite + }, + variables: {}, // Custom Mustache templating variables and functions + mode: { + css: { // CSS sprite mode + render: { + css: true // Render CSS stylesheet + } + }, + view: true, // Create a «view» sprite + defs: true, // Create a «defs» sprite + // symbol: true, // Create a «symbol» sprite + symbol: { // Create a «symbol» sprite + // dest: ".", + // inline: true, // Prepare for inline embedding + sprite: "unit.gl.svg" + }, + stack: true, // Create a «stack» sprite + // symbol: true // Symbol sprite mode + + } +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default svgspriteConfig; + + // "svgo": { + // "multipass": true, + // "plugins": [ + // { + // "name": "preset-default", + // "params": { + // "overrides": { + // "removeUnknownsAndDefaults": { + // "keepDataAttrs": false, + // "keepRoleAttr": true + // }, + // "removeViewBox": false + // } + // } + // }, + // "cleanupListOfValues", + // "removeXMLNS", + // { + // "name": "removeAttrs", + // "params": { + // "attrs": [ + // "clip-rule", + // "fill" + // ] + // } + // } + // ] + // } + + // : { + // dest: "", // Mode specific output directory + // prefix: "svg-%s", // Prefix for CSS selectors + // dimensions: "-dims", // Suffix for dimension CSS selectors + // sprite: "svg/sprite..svg", // Sprite path and name + // bust: true || false, // Cache busting (mode dependent default value) + // render: { // Stylesheet rendering definitions + // /* ------------------------------------------- + // css: false, // CSS stylesheet options + // scss: false, // Sass stylesheet options + // less: false, // LESS stylesheet options + // styl: false, // Stylus stylesheet options + // : ... // Custom stylesheet options + // ------------------------------------------- */ + // }, + // example: false // Create an HTML example document + // } \ No newline at end of file diff --git a/script/ts/config/terser.config.ts b/script/ts/config/terser.config.ts new file mode 100644 index 0000000..87268eb --- /dev/null +++ b/script/ts/config/terser.config.ts @@ -0,0 +1,28 @@ + + + +const terserCofig = { + compress: { + drop_console: true, // Remove console.log statements + drop_debugger: true, // Remove debugger statements + pure_funcs: ['console.info', 'console.debug', 'console.warn'], // Remove specific console functions + }, + mangle: { + // Mangle names for obfuscation and size reduction + properties: true, // Mangle property names + }, + format: { + comments: false, // Remove comments + beautify: false, // Disable beautification for smaller file size + }, + keep_classnames: false, // Remove class names + keep_fnames: false, // Remove function names + toplevel: true, // Enable top-level variable and function name mangling +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default terserCofig; diff --git a/script/ts/config/ts.config.ts b/script/ts/config/ts.config.ts new file mode 100644 index 0000000..d8b74bd --- /dev/null +++ b/script/ts/config/ts.config.ts @@ -0,0 +1,116 @@ + + + +const tsConfig = { + // allowImportingTsExtensions?: boolean; + // allowJs?: boolean; + // allowArbitraryExtensions?: boolean; + // allowSyntheticDefaultImports?: boolean; + // allowUmdGlobalAccess?: boolean; + // allowUnreachableCode?: boolean; + // allowUnusedLabels?: boolean; + // alwaysStrict?: boolean; + // baseUrl?: string; + // charset?: string; + // checkJs?: boolean; + // customConditions?: string[]; + // declaration?: boolean; + // declarationMap?: boolean; + // emitDeclarationOnly?: boolean; + // declarationDir?: string; + // disableSizeLimit?: boolean; + // disableSourceOfProjectReferenceRedirect?: boolean; + // disableSolutionSearching?: boolean; + // disableReferencedProjectLoad?: boolean; + // downlevelIteration?: boolean; + // emitBOM?: boolean; + // emitDecoratorMetadata?: boolean; + // exactOptionalPropertyTypes?: boolean; + // experimentalDecorators?: boolean; + // forceConsistentCasingInFileNames?: boolean; + // ignoreDeprecations?: string; + // importHelpers?: boolean; + // importsNotUsedAsValues?: ImportsNotUsedAsValues; + // inlineSourceMap?: boolean; + // inlineSources?: boolean; + // isolatedModules?: boolean; + // jsx?: JsxEmit; + // keyofStringsOnly?: boolean; + // lib?: string[]; + // locale?: string; + // mapRoot?: string; + // maxNodeModuleJsDepth?: number; + // module?: ModuleKind; + // moduleResolution?: ModuleResolutionKind; + // moduleSuffixes?: string[]; + // moduleDetection?: ModuleDetectionKind; + // newLine?: NewLineKind; + // noEmit?: boolean; + // noEmitHelpers?: boolean; + // noEmitOnError?: boolean; + // noErrorTruncation?: boolean; + // noFallthroughCasesInSwitch?: boolean; + // noImplicitAny?: boolean; + // noImplicitReturns?: boolean; + // noImplicitThis?: boolean; + // noStrictGenericChecks?: boolean; + // noUnusedLocals?: boolean; + // noUnusedParameters?: boolean; + // noImplicitUseStrict?: boolean; + // noPropertyAccessFromIndexSignature?: boolean; + // assumeChangesOnlyAffectDirectDependencies?: boolean; + // noLib?: boolean; + // noResolve?: boolean; + // noUncheckedIndexedAccess?: boolean; + // out?: string; + // outDir?: string; + // outFile: 'unit.gl.js' // string; + // paths?: MapLike; + // preserveConstEnums?: boolean; + // noImplicitOverride?: boolean; + // preserveSymlinks?: boolean; + // preserveValueImports?: boolean; + // project?: string; + // reactNamespace?: string; + // jsxFactory?: string; + // jsxFragmentFactory?: string; + // jsxImportSource?: string; + // composite?: boolean; + // incremental?: boolean; + // tsBuildInfoFile?: string; + // removeComments?: boolean; + // resolvePackageJsonExports?: boolean; + // resolvePackageJsonImports?: boolean; + // rootDir?: string; + // rootDirs?: string[]; + // skipLibCheck?: boolean; + // skipDefaultLibCheck?: boolean; + // sourceMap?: boolean; + // sourceRoot?: string; + // strict?: boolean; + // strictFunctionTypes?: boolean; + // strictBindCallApply?: boolean; + // strictNullChecks?: boolean; + // strictPropertyInitialization?: boolean; + // stripInternal?: boolean; + // suppressExcessPropertyErrors?: boolean; + // suppressImplicitAnyIndexErrors?: boolean; + // target?: ScriptTarget; + // traceResolution?: boolean; + // useUnknownInCatchVariables?: boolean; + // resolveJsonModule?: boolean; + // types?: string[]; + // /** Paths used to compute primary types search locations */ + // typeRoots?: string[]; + // verbatimModuleSyntax?: boolean; + // esModuleInterop?: boolean; + // useDefineForClassFields?: boolean; + // [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; +}; + + +// ============================================================================ +// Export +// ============================================================================ + +export default tsConfig; diff --git a/script/ts/index.ts b/script/ts/index.ts new file mode 100644 index 0000000..95033d8 --- /dev/null +++ b/script/ts/index.ts @@ -0,0 +1,183 @@ +// script/index.ts + +// Copyright 2023 Scape Agency BV + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// ============================================================================ +// Import +// ============================================================================ + +// Import necessary modules and classes +import path from 'path'; +import FontGenerator from './class/FontGenerator.js'; +import SvgPackager from "./class/SvgPackager.js"; +import StyleProcessor from "./class/StyleProcessor.js"; +import SvgSpriteGenerator from "./class/SvgSpriteGenerator.js"; +import PackageCreator from './class/PackageCreator.js'; +import VersionWriter from './class/VersionWriter.js'; +import FileCopier from './class/FileCopier.js'; +import FileRenamer from './class/FileRenamer.js'; +import DirectoryCreator from './class/DirectoryCreator.js'; +import DirectoryCopier from './class/DirectoryCopier.js'; +import DirectoryCleaner from './class/DirectoryCleaner.js'; // Adjust the path as needed +import TypeScriptCompiler from './class/TypeScriptCompiler.js'; +import JavaScriptMinifier from './class/JavaScriptMinifier.js'; + +// Import necessary configurations +import { CONFIG } from './config/config.js'; +import svgspriteConfig from "./config/svgsprite.config.js"; +import packageConfig from "./config/package.config.js" +import tsConfig from "./config/ts.config.js" +import tensorConfig from "./config/terser.config.js" + + +// ============================================================================ +// Constants +// ============================================================================ + +// Initialize instances of necessary classes +const directories = Object.values(CONFIG.path); +const spriteGenerator = new SvgSpriteGenerator(svgspriteConfig); +const tsCompiler = new TypeScriptCompiler(tsConfig); +const jsMinifier = new JavaScriptMinifier(tensorConfig); +const packageCreator = new PackageCreator(packageConfig); +const svgPackager = new SvgPackager(); +const fontGenerator = new FontGenerator(); +const styleProcessor = new StyleProcessor(); +const versionWriter = new VersionWriter(); +const fileCopier = new FileCopier(); +const fileRenamer = new FileRenamer(); +const directoryCopier = new DirectoryCopier(); +const directoryCleaner = new DirectoryCleaner(); +const directoryCreator = new DirectoryCreator(); + + +// ============================================================================ +// Functions +// ============================================================================ + +/** + * Main function to orchestrate the various processes. + * It handles SVG processing, font generation, SVG sprite generation, and SASS + * processing. + */ +async function main() { + + try { + + + // Dirs Clean + // -------------------------------------------------------------------- + directoryCleaner.cleanDirectory(CONFIG.path.dist); + console.log(`Directory cleaned: ${CONFIG.path.dist}`); + + // Dirs Create + // -------------------------------------------------------------------- + console.log('Starting Directory creation...'); + // Assuming the base path is the current directory + await directoryCreator.createDirectories('.', directories); + + + + // Copy Dirs + // -------------------------------------------------------------------- + try { + await directoryCopier.recursiveCopy( + CONFIG.path.ts_input, + CONFIG.path.ts_output, + ); + console.log('Files copied successfully.'); + } catch (error) { + console.error('Error while copying files:', error); + } + + + // Version + // -------------------------------------------------------------------- + await versionWriter.writeVersionToFile('VERSION', packageConfig.version); + + + // Package JSON + // -------------------------------------------------------------------- + + await packageCreator.createPackageJson(CONFIG.path.dist); + + + // Compile TypeScript to JavaScript + // -------------------------------------------------------------------- + + + try { + // Other code... + + // TypeScript compilation + const tsFiles = [ + path.join(CONFIG.path.ts_input, 'index.ts'), + // './src/ts/index.ts', + // './src/ts/file1.ts', + // './src/ts/file2.ts' + ]; // Replace with actual file paths + const outputDir = './dist/js'; + + console.log('Starting TypeScript compilation...'); + tsCompiler.compile(tsFiles, outputDir); + console.log('TypeScript compilation completed.'); + + // Other code... + } catch (error) { + console.error('An error occurred:', error); + } + + + // Rename Ts + // -------------------------------------------------------------------- + + await fileRenamer.renameFile( + path.join(CONFIG.path.js_output, 'index.js'), + path.join(CONFIG.path.js_output, 'pack.gl.js'), + ) + + // Minify JavaScript + // -------------------------------------------------------------------- + + + // const inputJsFile = './path/to/your/script.js'; + // const outputMinJsFile = './path/to/your/script.min.js'; + + await jsMinifier.minifyFile( + path.join(CONFIG.path.js_output, 'pack.gl.js'), + path.join(CONFIG.path.js_output, 'pack.gl.min.js'), + // inputJsFile, + // outputMinJsFile + ) + .then(() => console.log('JavaScript minification completed.')) + .catch(console.error); + + + + + } catch (error) { + console.error('An error occurred:', error); + } + +} + + +// ============================================================================ +// Main +// ============================================================================ + +// Execute the main function +main(); diff --git a/script/ts/interfaces/File.ts b/script/ts/interfaces/File.ts new file mode 100644 index 0000000..4f47dc8 --- /dev/null +++ b/script/ts/interfaces/File.ts @@ -0,0 +1,4 @@ +interface File { + filepath: string; + source: string; +} \ No newline at end of file diff --git a/script/ts/interfaces/PackageJson.ts b/script/ts/interfaces/PackageJson.ts new file mode 100644 index 0000000..15078de --- /dev/null +++ b/script/ts/interfaces/PackageJson.ts @@ -0,0 +1,70 @@ +// ============================================================================ +// Interfaces +// ============================================================================ + +interface PackageJson { + name: string; + version: string; + description?: string; + main?: string; + scripts?: Record; + dependencies?: Record; + devDependencies?: Record; + repository?: { + type: string; + url: string; + }; + keywords?: string[]; + author?: string | { + name: string; + email?: string; + url?: string; + }; + license?: string; + bugs?: { + url?: string; + email?: string; + }; + homepage?: string; + private?: boolean; + peerDependencies?: Record; + engines?: { + node?: string; + npm?: string; + }; + bin?: Record; + types?: string; + contributors?: Array; + funding?: string | { + type: string; + url: string; + }; + files?: string[]; + browserslist?: string[] | Record; + publishConfig?: Record; + config?: Record; + typings?: string; + exports?: Record; + module?: string; + sideEffects?: boolean | string[]; + + optionalDependencies?: Record; + bundledDependencies?: string[]; // or bundleDependencies + peerDependenciesMeta?: Record; + resolutions?: Record; + workspaces?: string[] | { + packages: string[]; + }; + eslintConfig?: Record; + babel?: Record; + prettier?: Record; + husky?: Record; + jest?: Record; + enginesStrict?: boolean; + os?: string[]; + cpu?: string[]; +} diff --git a/script/ts/interfaces/SVG.ts b/script/ts/interfaces/SVG.ts new file mode 100644 index 0000000..4a18efa --- /dev/null +++ b/script/ts/interfaces/SVG.ts @@ -0,0 +1,12 @@ + + + +// Assuming the structure of your SVG object, you might need to adjust these types +interface Svg { + metadata: { + name: string; + // ... other metadata properties + }; + source: string; + // ... other Svg properties + } \ No newline at end of file diff --git a/script/tsconfig.json b/script/tsconfig.json new file mode 100644 index 0000000..4e376b4 --- /dev/null +++ b/script/tsconfig.json @@ -0,0 +1,99 @@ +// tsconfig.json + +{ + + "$schema": "https://json.schemastore.org/tsconfig", + "display": "ESM", + + "compilerOptions": { + + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Language and Environment */ + "target": "es2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "lib": ["esnext", "es2017", "ES2015", "dom"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + + /* Modules */ + "module": "esnext", /* Specify what module code is generated. */ + "rootDir": "./ts", /* Specify the root folder within your source files. */ + "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + //"baseUrl": "src" /* Specify the base directory to resolve non-relative module names. */, + // "paths": { + // "@/*": ["./*"], + // "#/*": ["./*"] + // }, + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": [ /* Specify multiple folders that act like `./node_modules/@types`. */ + "node_modules/@types" + ], + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + "resolveJsonModule": true, /* Enable importing .json files */ + // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */, + "checkJs": false /* Enable error reporting in type-checked JavaScript files. */, + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./js", /* Specify an output folder for all emitted files. */ + "removeComments": true, /* Disable emitting comments. */ + "noImplicitReturns": true, + "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + "downlevelIteration": false, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + "noEmitOnError": false, /* Disable emitting files if any type checking errors are reported. */ + + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + + /* Type Checking */ + "strict": true /* Enable all strict type-checking options. */, + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ + "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ + "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ + "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + + /* Completeness */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + + }, + + "ts-node": { + "esm": true, + "experimentalSpecifierResolution": "node" + }, + + "include": [ + // "src/**/*", + // "src/**/*.ts", + // "script/**/*", + // "src/index.ts.xxx", + // "src/index.ts.xxx", + // "script/release.ts", + "./ts/**/*.ts", + // "tmp/SvgOptimizer.ts", + + ], + + "exclude": [ + "**/*.spec.ts", + "node_modules", + "dist", + "public", + "build", + "tmp" + ] + +}