@helloao/cli 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helloao/cli",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "A CLI and related tools for managing HelloAO's Free Bible API",
5
5
  "module": "index.js",
6
6
  "types": "index.d.ts",
package/actions.d.ts DELETED
@@ -1,121 +0,0 @@
1
- import { UploadApiFromDatabaseOptions, UploadApiOptions } from './uploads';
2
- export interface InitDbOptions {
3
- /**
4
- * The path to the source database to copy the schema from.
5
- */
6
- source?: string;
7
- /**
8
- * The languages to copy from the source database. If not specified, then all languages will be copied.
9
- */
10
- language?: string[];
11
- }
12
- /**
13
- * Initializes a new Bible API DB.
14
- * @param dbPath The path to the database. If null or empty, then the "bible-api.db" will be used from the current working directory.
15
- * @param options The options for the initialization.
16
- */
17
- export declare function initDb(dbPath: string | null, options: InitDbOptions): Promise<void>;
18
- export interface ImportTranslationOptions {
19
- /**
20
- * Whether to forcibly import the translations, even if they have already been imported.
21
- */
22
- overwrite?: boolean;
23
- }
24
- /**
25
- * Imports a translation from the given directory into the database in the current working directory.
26
- * @param dir The directory that the translation is located in.
27
- * @param dirs Any extra directories that should be imported.
28
- * @param options The options for the import.
29
- */
30
- export declare function importTranslation(dir: string, dirs: string[], options: ImportTranslationOptions): Promise<void>;
31
- /**
32
- * Imports all the translations from the given directory into the database in the current working directory.
33
- * @param dir The directory that the translations are located in.
34
- * @param options The options.
35
- */
36
- export declare function importTranslations(dir: string, options: ImportTranslationOptions): Promise<void>;
37
- export interface FetchTranslationsOptions {
38
- /**
39
- * Fetch all translations. If omitted, only undownloaded translations will be fetched.
40
- */
41
- all?: boolean;
42
- }
43
- /**
44
- * Fetches the specified translations from fetch.bible and places them in the given directory.
45
- * @param dir The directory that the translations should be placed in.
46
- * @param translations The translations that should be downloaded. If not specified, then all translations will be downloaded.
47
- * @param options The options.
48
- */
49
- export declare function fetchTranslations(dir: string, translations?: string[], options?: FetchTranslationsOptions): Promise<void>;
50
- /**
51
- * Fetches the specified audio translations and places them in the given directory.
52
- * Translations should be in the format "translationId/audioId". e.g. "BSB/gilbert"
53
- * @param dir The directory that the translations should be placed in.
54
- * @param translations The translations that should be downloaded.
55
- * @param options The options.
56
- */
57
- export declare function fetchAudio(dir: string, translations: string[], options?: FetchTranslationsOptions): Promise<void>;
58
- /**
59
- * Generates the translation files directly from the translations stored in the given input directory.
60
- * @param input The input directory that the translations are stored in.
61
- * @param dest The destination to upload the API files to.
62
- * @param options The options for the generation.
63
- */
64
- export declare function generateTranslationsFiles(input: string, dest: string, options: UploadApiFromDatabaseOptions): Promise<void>;
65
- /**
66
- * Generates the translation files directly from the translation stored in the given input directory.
67
- * @param input The input directory that the translation is stored in.
68
- * @param dest The destination to upload the API files to.
69
- * @param options The options for the generation.
70
- */
71
- export declare function generateTranslationFiles(input: string, dest: string, options: UploadApiOptions): Promise<void>;
72
- /**
73
- * The options for uploading the test translations.
74
- */
75
- export interface UploadTestTranslationOptions extends UploadApiOptions {
76
- /**
77
- * The s3 URL to upload the translations to.
78
- * Defaults to "s3://ao-bible-api-public-uploads"
79
- */
80
- s3Url?: string;
81
- }
82
- export interface UploadTestTranslationResult {
83
- /**
84
- * The S3 URL where the translations were uploaded to.
85
- */
86
- uploadS3Url: string;
87
- /**
88
- * The HTTP URL that the version can be accessed at.
89
- */
90
- url: string;
91
- /**
92
- * The URL that the available translations can be accessed at.
93
- */
94
- availableTranslationsUrl: string;
95
- /**
96
- * The version that was uploaded.
97
- * This is a SHA-256 hash of the input files.
98
- */
99
- version: string;
100
- }
101
- /**
102
- * Generates the API files directly from the translations stored in the given input directory and
103
- * uploads them to the HelloAO test s3 bucket.
104
- *
105
- * Requires access to the HelloAO test s3 bucket. Email hello@helloao.org for access.
106
- *
107
- * @param input The input directory that the translations are stored in.
108
- * @param options The options to use for the upload.
109
- */
110
- export declare function uploadTestTranslations(input: string, options: UploadTestTranslationOptions): Promise<UploadTestTranslationResult>;
111
- /**
112
- * Generates the API files directly from the given translation and
113
- * uploads them to the HelloAO test s3 bucket.
114
- *
115
- * Requires access to the HelloAO test s3 bucket. Email hello@helloao.org for access.
116
- *
117
- * @param input The input directory that the translations are stored in.
118
- * @param options The options to use for the upload.
119
- */
120
- export declare function uploadTestTranslation(input: string, options: UploadTestTranslationOptions): Promise<UploadTestTranslationResult>;
121
- //# sourceMappingURL=actions.d.ts.map
package/actions.js DELETED
@@ -1,378 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.initDb = initDb;
30
- exports.importTranslation = importTranslation;
31
- exports.importTranslations = importTranslations;
32
- exports.fetchTranslations = fetchTranslations;
33
- exports.fetchAudio = fetchAudio;
34
- exports.generateTranslationsFiles = generateTranslationsFiles;
35
- exports.generateTranslationFiles = generateTranslationFiles;
36
- exports.uploadTestTranslations = uploadTestTranslations;
37
- exports.uploadTestTranslation = uploadTestTranslation;
38
- const node_path_1 = __importStar(require("node:path"));
39
- const database = __importStar(require("./db"));
40
- const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
41
- const linkedom_1 = require("linkedom");
42
- const promises_1 = require("node:fs/promises");
43
- const fetch_client_1 = require("@gracious.tech/fetch-client");
44
- const utils_1 = require("@helloao/tools/utils");
45
- const fs_extra_1 = require("fs-extra");
46
- const audio_1 = require("@helloao/tools/generation/audio");
47
- const book_order_1 = require("@helloao/tools/generation/book-order");
48
- const downloads_1 = require("./downloads");
49
- const iterators_1 = require("@helloao/tools/parser/iterators");
50
- const files_1 = require("./files");
51
- const dataset_1 = require("@helloao/tools/generation/dataset");
52
- const uploads_1 = require("./uploads");
53
- const s3_1 = require("./s3");
54
- /**
55
- * Initializes a new Bible API DB.
56
- * @param dbPath The path to the database. If null or empty, then the "bible-api.db" will be used from the current working directory.
57
- * @param options The options for the initialization.
58
- */
59
- async function initDb(dbPath, options) {
60
- console.log('Initializing new Bible API DB...');
61
- if (options.source) {
62
- const db = new better_sqlite3_1.default(database.getDbPath(dbPath), {});
63
- const sourcePath = node_path_1.default.resolve(options.source);
64
- try {
65
- console.log('Copying schema from source DB...');
66
- if (options.language) {
67
- console.log('Copying only the following languages:', options.language);
68
- const languages = `(${options.language
69
- .map((l) => `'${l}'`)
70
- .join(', ')})`;
71
- db.exec(`
72
- ATTACH DATABASE "${sourcePath}" AS source;
73
-
74
- CREATE TABLE "_prisma_migrations" AS SELECT * FROM source._prisma_migrations;
75
-
76
- CREATE TABLE "Translation" AS SELECT * FROM source.Translation
77
- WHERE language IN ${languages};
78
-
79
- CREATE TABLE "Book" AS SELECT * FROM source.Book
80
- INNER JOIN source.Translation ON source.Translation.id = source.Book.translationId
81
- WHERE source.Translation.language IN ${languages};
82
-
83
- CREATE TABLE "Chapter" AS SELECT * FROM source.Chapter
84
- INNER JOIN source.Translation ON source.Translation.id = source.Chapter.translationId
85
- WHERE source.Translation.language IN ${languages};
86
-
87
- CREATE TABLE "ChapterVerse" AS SELECT * FROM source.ChapterVerse
88
- INNER JOIN source.Translation ON source.Translation.id = source.ChapterVerse.translationId
89
- WHERE source.Translation.language IN ${languages};
90
-
91
- CREATE TABLE "ChapterFootnote" AS SELECT * FROM source.ChapterFootnote
92
- INNER JOIN source.Translation ON source.Translation.id = source.ChapterFootnote.translationId
93
- WHERE source.Translation.language IN ${languages};
94
-
95
- CREATE TABLE "ChapterAudioUrl" AS SELECT * FROM source.ChapterAudioUrl
96
- INNER JOIN source.Translation ON source.Translation.id = source.ChapterAudioUrl.translationId
97
- WHERE source.Translation.language IN ${languages};
98
- `);
99
- }
100
- else {
101
- db.exec(`
102
- ATTACH DATABASE "${sourcePath}" AS source;
103
-
104
- CREATE TABLE "_prisma_migrations" AS SELECT * FROM source._prisma_migrations;
105
- CREATE TABLE "Translation" AS SELECT * FROM source.Translation;
106
- CREATE TABLE "Book" AS SELECT * FROM source.Book;
107
- CREATE TABLE "Chapter" AS SELECT * FROM source.Chapter;
108
- CREATE TABLE "ChapterVerse" AS SELECT * FROM source.ChapterVerse;
109
- CREATE TABLE "ChapterFootnote" AS SELECT * FROM source.ChapterFootnote;
110
- CREATE TABLE "ChapterAudioUrl" AS SELECT * FROM source.ChapterAudioUrl;
111
- `);
112
- }
113
- console.log('Done.');
114
- }
115
- finally {
116
- db.close();
117
- }
118
- }
119
- else {
120
- const db = await database.getDb(database.getDbPath(dbPath));
121
- db.close();
122
- }
123
- }
124
- /**
125
- * Imports a translation from the given directory into the database in the current working directory.
126
- * @param dir The directory that the translation is located in.
127
- * @param dirs Any extra directories that should be imported.
128
- * @param options The options for the import.
129
- */
130
- async function importTranslation(dir, dirs, options) {
131
- const parser = new linkedom_1.DOMParser();
132
- globalThis.DOMParser = linkedom_1.DOMParser;
133
- globalThis.Element = linkedom_1.Element;
134
- globalThis.Node = linkedom_1.Node;
135
- const db = await database.getDbFromDir(process.cwd());
136
- try {
137
- await database.importTranslations(db, [dir, ...dirs], parser, !!options.overwrite);
138
- }
139
- finally {
140
- db.close();
141
- }
142
- }
143
- /**
144
- * Imports all the translations from the given directory into the database in the current working directory.
145
- * @param dir The directory that the translations are located in.
146
- * @param options The options.
147
- */
148
- async function importTranslations(dir, options) {
149
- const parser = new linkedom_1.DOMParser();
150
- globalThis.DOMParser = linkedom_1.DOMParser;
151
- globalThis.Element = linkedom_1.Element;
152
- globalThis.Node = linkedom_1.Node;
153
- const db = await database.getDbFromDir(process.cwd());
154
- try {
155
- const files = await (0, promises_1.readdir)(dir);
156
- const translationDirs = files.map((f) => node_path_1.default.resolve(dir, f));
157
- console.log(`Importing ${translationDirs.length} translations`);
158
- await database.importTranslations(db, translationDirs, parser, !!options.overwrite);
159
- }
160
- finally {
161
- db.close();
162
- }
163
- }
164
- /**
165
- * Fetches the specified translations from fetch.bible and places them in the given directory.
166
- * @param dir The directory that the translations should be placed in.
167
- * @param translations The translations that should be downloaded. If not specified, then all translations will be downloaded.
168
- * @param options The options.
169
- */
170
- async function fetchTranslations(dir, translations, options = {}) {
171
- const translationsSet = new Set(translations);
172
- const client = new fetch_client_1.BibleClient({
173
- remember_fetches: false,
174
- });
175
- const collection = await client.fetch_collection();
176
- const collectionTranslations = collection.get_translations();
177
- console.log(`Discovered ${collectionTranslations.length} translations`);
178
- const filtered = translations && translations.length <= 0
179
- ? collectionTranslations
180
- : collectionTranslations.filter((t) => translationsSet.has(t.id));
181
- let batches = [];
182
- while (filtered.length > 0) {
183
- batches.push(filtered.splice(0, 10));
184
- }
185
- console.log(`Downloading ${filtered.length} translations in ${batches.length} batches`);
186
- for (let i = 0; i < batches.length; i++) {
187
- const batch = batches[i];
188
- console.log(`Downloading batch ${i + 1} of ${batches.length}`);
189
- const translations = await Promise.all(batch.map(async (t) => {
190
- const id = (0, utils_1.getTranslationId)(t.id);
191
- const translation = {
192
- id,
193
- name: (0, utils_1.getFirstNonEmpty)(t.name_local, t.name_english, t.name_abbrev),
194
- direction: (0, utils_1.getFirstNonEmpty)(t.direction, 'ltr'),
195
- englishName: (0, utils_1.getFirstNonEmpty)(t.name_english, t.name_abbrev, t.name_local),
196
- language: (0, utils_1.normalizeLanguage)(t.language),
197
- licenseUrl: t.attribution_url,
198
- shortName: (0, utils_1.getFirstNonEmpty)(t.name_abbrev, id),
199
- website: t.attribution_url,
200
- };
201
- const books = await Promise.all(collection.get_books(t.id).map(async (b) => {
202
- const name = `${b.id}.usx`;
203
- if (!options.all &&
204
- (await (0, fs_extra_1.exists)(node_path_1.default.resolve(dir, translation.id, name)))) {
205
- return null;
206
- }
207
- const content = await collection.fetch_book(t.id, b.id, 'usx');
208
- const contentString = content.get_whole();
209
- const file = {
210
- fileType: 'usx',
211
- content: contentString,
212
- metadata: {
213
- translation,
214
- },
215
- name,
216
- };
217
- return file;
218
- }));
219
- return {
220
- translation,
221
- books,
222
- };
223
- }));
224
- console.log(`Writing batch ${i + 1} of ${batches.length}`);
225
- let promises = [];
226
- for (let { translation, books } of translations) {
227
- for (let book of books) {
228
- if (!book) {
229
- continue;
230
- }
231
- if (!book.name) {
232
- throw new Error('Book name is required');
233
- }
234
- const fullPath = node_path_1.default.resolve(dir, translation.id, book.name);
235
- await (0, promises_1.mkdir)(node_path_1.default.dirname(fullPath), { recursive: true });
236
- const promise = (0, promises_1.writeFile)(fullPath, book.content);
237
- promises.push(promise);
238
- }
239
- const translationPath = node_path_1.default.resolve(dir, translation.id, 'metadata.json');
240
- await (0, promises_1.mkdir)(node_path_1.default.dirname(translationPath), { recursive: true });
241
- const translationData = JSON.stringify(translation, null, 2);
242
- promises.push((0, promises_1.writeFile)(translationPath, translationData));
243
- }
244
- await Promise.all(promises);
245
- }
246
- }
247
- /**
248
- * Fetches the specified audio translations and places them in the given directory.
249
- * Translations should be in the format "translationId/audioId". e.g. "BSB/gilbert"
250
- * @param dir The directory that the translations should be placed in.
251
- * @param translations The translations that should be downloaded.
252
- * @param options The options.
253
- */
254
- async function fetchAudio(dir, translations, options = {}) {
255
- for (let translation of translations) {
256
- const [translationId, reader] = translation.split('/');
257
- const generator = audio_1.KNOWN_AUDIO_TRANSLATIONS.get(translationId)?.get(reader);
258
- if (!generator) {
259
- console.warn('Unknown translation:', translation);
260
- continue;
261
- }
262
- for (let [bookId, chapters] of book_order_1.bookChapterCountMap) {
263
- for (let chapter = 1; chapter <= chapters; chapter++) {
264
- const url = generator(bookId, chapter);
265
- const ext = (0, node_path_1.extname)(url);
266
- const [translationId, reader] = translation.split('/');
267
- const name = `${chapter}.${reader}${ext}`;
268
- const fullPath = node_path_1.default.resolve(dir, 'audio', translationId, bookId, name);
269
- if (!options.all && (await (0, fs_extra_1.exists)(fullPath))) {
270
- continue;
271
- }
272
- await (0, downloads_1.downloadFile)(url, fullPath);
273
- }
274
- }
275
- }
276
- }
277
- /**
278
- * Generates the translation files directly from the translations stored in the given input directory.
279
- * @param input The input directory that the translations are stored in.
280
- * @param dest The destination to upload the API files to.
281
- * @param options The options for the generation.
282
- */
283
- async function generateTranslationsFiles(input, dest, options) {
284
- const parser = new linkedom_1.DOMParser();
285
- globalThis.DOMParser = linkedom_1.DOMParser;
286
- globalThis.Element = linkedom_1.Element;
287
- globalThis.Node = linkedom_1.Node;
288
- const dirs = await (0, promises_1.readdir)(node_path_1.default.resolve(input));
289
- const batchSize = typeof options.batchSize === 'number'
290
- ? options.batchSize
291
- : parseInt(options.batchSize);
292
- for (let b of (0, iterators_1.batch)(dirs, batchSize)) {
293
- const files = await (0, files_1.loadTranslationsFiles)(b);
294
- const dataset = (0, dataset_1.generateDataset)(files, parser);
295
- await (0, uploads_1.serializeAndUploadDatasets)(dest, (0, iterators_1.toAsyncIterable)([dataset]), options);
296
- }
297
- }
298
- /**
299
- * Generates the translation files directly from the translation stored in the given input directory.
300
- * @param input The input directory that the translation is stored in.
301
- * @param dest The destination to upload the API files to.
302
- * @param options The options for the generation.
303
- */
304
- async function generateTranslationFiles(input, dest, options) {
305
- const parser = new linkedom_1.DOMParser();
306
- globalThis.DOMParser = linkedom_1.DOMParser;
307
- globalThis.Element = linkedom_1.Element;
308
- globalThis.Node = linkedom_1.Node;
309
- const files = await (0, files_1.loadTranslationFiles)(node_path_1.default.resolve(input));
310
- const dataset = (0, dataset_1.generateDataset)(files, parser);
311
- await (0, uploads_1.serializeAndUploadDatasets)(dest, (0, iterators_1.toAsyncIterable)([dataset]), options);
312
- }
313
- /**
314
- * Generates the API files directly from the translations stored in the given input directory and
315
- * uploads them to the HelloAO test s3 bucket.
316
- *
317
- * Requires access to the HelloAO test s3 bucket. Email hello@helloao.org for access.
318
- *
319
- * @param input The input directory that the translations are stored in.
320
- * @param options The options to use for the upload.
321
- */
322
- async function uploadTestTranslations(input, options) {
323
- const parser = new linkedom_1.DOMParser();
324
- globalThis.DOMParser = linkedom_1.DOMParser;
325
- globalThis.Element = linkedom_1.Element;
326
- globalThis.Node = linkedom_1.Node;
327
- const dirs = await (0, promises_1.readdir)(node_path_1.default.resolve(input));
328
- const files = await (0, files_1.loadTranslationsFiles)(dirs);
329
- const hash = (0, files_1.hashInputFiles)(files);
330
- const dataset = (0, dataset_1.generateDataset)(files, parser);
331
- const url = options.s3Url || 's3://ao-bible-api-public-uploads';
332
- await (0, uploads_1.serializeAndUploadDatasets)(url, (0, iterators_1.toAsyncIterable)([dataset]), {
333
- ...options,
334
- pathPrefix: `/${hash}`,
335
- });
336
- const urls = getUrls(url);
337
- return {
338
- ...urls,
339
- version: hash,
340
- availableTranslationsUrl: `${urls.url}/${hash}/api/available_translations.json`,
341
- };
342
- }
343
- /**
344
- * Generates the API files directly from the given translation and
345
- * uploads them to the HelloAO test s3 bucket.
346
- *
347
- * Requires access to the HelloAO test s3 bucket. Email hello@helloao.org for access.
348
- *
349
- * @param input The input directory that the translations are stored in.
350
- * @param options The options to use for the upload.
351
- */
352
- async function uploadTestTranslation(input, options) {
353
- const parser = new linkedom_1.DOMParser();
354
- globalThis.DOMParser = linkedom_1.DOMParser;
355
- globalThis.Element = linkedom_1.Element;
356
- globalThis.Node = linkedom_1.Node;
357
- const files = await (0, files_1.loadTranslationFiles)(node_path_1.default.resolve(input));
358
- const hash = (0, files_1.hashInputFiles)(files);
359
- const dataset = (0, dataset_1.generateDataset)(files, parser);
360
- const url = options.s3Url || 's3://ao-bible-api-public-uploads';
361
- await (0, uploads_1.serializeAndUploadDatasets)(url, (0, iterators_1.toAsyncIterable)([dataset]), {
362
- ...options,
363
- pathPrefix: `/${hash}`,
364
- });
365
- const urls = getUrls(url);
366
- return {
367
- ...urls,
368
- version: hash,
369
- availableTranslationsUrl: `${urls.url}/${hash}/api/available_translations.json`,
370
- };
371
- }
372
- function getUrls(dest) {
373
- const url = (0, s3_1.getHttpUrl)(dest);
374
- return {
375
- uploadS3Url: dest,
376
- url: url,
377
- };
378
- }
package/cli.d.ts DELETED
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
3
- //# sourceMappingURL=cli.d.ts.map