UNPKG

sheets-translate-to-json

Version:

A Node.js library that facilitates the retrieval and conversion of previously translated Google Sheets spreadsheets into structured JSON files, optimizing the management of localized resources.

237 lines (236 loc) 8.28 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts var src_exports = {}; __export(src_exports, { SheetManager: () => SheetManager }); module.exports = __toCommonJS(src_exports); var import_google_spreadsheet = require("google-spreadsheet"); var import_google_auth_library = require("google-auth-library"); var import_fs = __toESM(require("fs")); var import_path = __toESM(require("path")); var SheetManager = class { constructor(privateKey, clientEmail, sheetId) { const SCOPES = [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive.file" ]; this.jwt = new import_google_auth_library.JWT({ email: clientEmail, key: privateKey, scopes: SCOPES }); this.doc = new import_google_spreadsheet.GoogleSpreadsheet(sheetId, this.jwt); } init(userPath, sheetNames) { return __async(this, null, function* () { try { yield this.jwt.authorize(); if (sheetNames && sheetNames.length > 0) { const combinedData = {}; for (const sheetName of sheetNames) { const data = yield this.readByName(sheetName); if (data && Object.keys(data).length > 0) { Object.keys(data).forEach((language) => { if (!combinedData[language]) { combinedData[language] = {}; } this.mergeNestedObjects(combinedData[language], data[language]); }); } else { console.warn(`No data found in sheet: ${sheetName}`); } } if (Object.keys(combinedData).length > 0) { this.write(combinedData, userPath); } } else { const allSheetsData = yield this.readAllSheets(); const combinedData = {}; Object.keys(allSheetsData).forEach((sheetName) => { const sheetData = allSheetsData[sheetName]; Object.keys(sheetData).forEach((language) => { if (!combinedData[language]) { combinedData[language] = {}; } this.mergeNestedObjects(combinedData[language], sheetData[language]); }); }); if (Object.keys(combinedData).length > 0) { this.write(combinedData, userPath); } else { console.error("No data found in the sheet"); } } } catch (err) { console.error("Error during initialization:", err); } }); } read(sheetPosition = 0) { return __async(this, null, function* () { if (sheetPosition < 0) { sheetPosition = 0; } yield this.doc.loadInfo(); const sheet = this.doc.sheetsByIndex[sheetPosition]; return this.processSheet(sheet); }); } readByName(sheetName) { return __async(this, null, function* () { yield this.doc.loadInfo(); const sheet = this.doc.sheetsByTitle[sheetName]; if (!sheet) { throw new Error(`Sheet with name "${sheetName}" not found`); } return this.processSheet(sheet); }); } readAllSheets() { return __async(this, null, function* () { yield this.doc.loadInfo(); const allData = {}; for (const sheet of this.doc.sheetsByIndex) { try { const data = yield this.processSheet(sheet); if (data && Object.keys(data).length > 0) { allData[sheet.title] = data; } } catch (error) { console.error(`Error processing sheet "${sheet.title}":`, error); } } return allData; }); } processSheet(sheet) { return __async(this, null, function* () { yield sheet.loadHeaderRow(); const colTitles = sheet.headerValues; const rows = yield sheet.getRows({ limit: sheet.rowCount }); const result = {}; rows.forEach((row) => { const keyValue = row.get(colTitles[0]); if (!keyValue || keyValue.trim() === "") { return; } colTitles.slice(1).forEach((title) => { const key = keyValue.trim(); const value = row.get(title); const cleanValue = value && value.trim() !== "" ? value.trim() : void 0; if (!result[title]) { result[title] = {}; } if (key.includes(".")) { this.setNestedValue(result[title], key, cleanValue); } else { result[title][key] = cleanValue; } }); }); return result; }); } setNestedValue(obj, keyPath, value) { const keys = keyPath.split("."); let current = obj; for (let i = 0; i < keys.length - 1; i++) { const key = keys[i]; if (!current[key] || typeof current[key] !== "object") { current[key] = {}; } current = current[key]; } const finalKey = keys[keys.length - 1]; current[finalKey] = value; } mergeNestedObjects(target, source) { for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { const sourceValue = source[key]; const targetValue = target[key]; if (typeof sourceValue === "object" && sourceValue !== null && typeof targetValue === "object" && targetValue !== null) { this.mergeNestedObjects(targetValue, sourceValue); } else { target[key] = sourceValue; } } } } write(data, directoryPath) { if (!import_fs.default.existsSync(directoryPath)) { import_fs.default.mkdirSync(directoryPath, { recursive: true }); } Object.keys(data).forEach((key) => { const fileName = `${key}.json`; const filePath = import_path.default.join(directoryPath, fileName); import_fs.default.writeFile(filePath, JSON.stringify(data[key], null, 2), (err) => { if (err) { console.error(`Error writing file ${filePath}:`, err); return; } console.log(`File written: ${filePath}`); }); }); } // Méthode utilitaire pour lister toutes les feuilles disponibles listSheets() { return __async(this, null, function* () { yield this.doc.loadInfo(); return this.doc.sheetsByIndex.map((sheet) => sheet.title); }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { SheetManager }); //# sourceMappingURL=index.js.map