@learnpack/learnpack 5.0.310 → 5.0.312

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.
@@ -1,517 +1,533 @@
1
- /* eslint-disable arrow-parens */
2
- /* eslint-disable unicorn/no-array-for-each */
3
- import { execSync } from "child_process"
4
- import { flags } from "@oclif/command"
5
- import SessionCommand from "../utils/SessionCommand"
6
- import SessionManager from "../managers/session"
7
- import * as fs from "fs"
8
- import * as path from "path"
9
- import * as archiver from "archiver"
10
- import axios from "axios"
11
- import FormData = require("form-data")
12
- import Console from "../utils/console"
13
- import {
14
- decompress,
15
- downloadEditor,
16
- checkIfDirectoryExists,
17
- } from "../managers/file"
18
- import api, { getConsumable, RIGOBOT_HOST, TAcademy } from "../utils/api"
19
- import * as prompts from "prompts"
20
- import { isValidRigoToken } from "../utils/rigoActions"
21
- import { minutesToISO8601Duration } from "../utils/misc"
22
- import { slugify } from "../utils/creatorUtilities"
23
-
24
- const uploadZipEndpont = RIGOBOT_HOST + "/v1/learnpack/upload"
25
-
26
- export const handleAssetCreation = async (
27
- sessionPayload: { token: string; rigobotToken: string },
28
- learnJson: any,
29
- selectedLang: string,
30
- learnpackDeployUrl: string,
31
- b64IndexReadme: string,
32
- all_translations: string[] = []
33
- ) => {
34
- const category = "uncategorized"
35
-
36
- try {
37
- const user = await api.validateToken(sessionPayload.token)
38
-
39
- let slug = slugify(learnJson.title[selectedLang]).slice(0, 47)
40
- slug = `${slug}-${selectedLang}`
41
-
42
- const { exists } = await api.doesAssetExists(sessionPayload.token, slug)
43
-
44
- if (!exists) {
45
- Console.info("Asset does not exist in this academy, creating it")
46
- const asset = await api.createAsset(sessionPayload.token, {
47
- slug: slug,
48
- title: learnJson.title[selectedLang],
49
- lang: selectedLang,
50
- description: learnJson.description[selectedLang],
51
- learnpack_deploy_url: learnpackDeployUrl,
52
- technologies: learnJson.technologies.map((tech: string) =>
53
- tech.toLowerCase().replace(/\s+/g, "-")
54
- ),
55
- url: learnpackDeployUrl,
56
- category: category,
57
- owner: user.id,
58
- author: user.id,
59
- preview: learnJson.preview,
60
- readme_raw: b64IndexReadme,
61
- all_translations,
62
- })
63
- await api.updateRigoPackage(sessionPayload.token, learnJson.slug, {
64
- asset_id: asset.id,
65
- })
66
- Console.info("Asset created with id", asset.id)
67
- return asset
68
- }
69
-
70
- Console.info("Asset exists, updating it")
71
- const asset = await api.updateAsset(sessionPayload.token, slug, {
72
- learnpack_deploy_url: learnpackDeployUrl,
73
- title: learnJson.title[selectedLang],
74
- category: category,
75
- description: learnJson.description[selectedLang],
76
- all_translations,
77
- })
78
- await api.updateRigoPackage(
79
- sessionPayload.rigobotToken.trim(),
80
- learnJson.slug,
81
- {
82
- asset_id: asset.id,
83
- }
84
- )
85
- Console.info("Asset updated with id", asset.id)
86
- return asset
87
- } catch (error) {
88
- Console.error("Error updating or creating asset:", error)
89
- return null
90
- }
91
- }
92
-
93
- const runAudit = (strict: boolean) => {
94
- try {
95
- Console.info("Running learnpack audit before publishing...")
96
- execSync(`learnpack audit ${strict ? "--strict" : ""}`, {
97
- stdio: "inherit",
98
- })
99
- } catch (error) {
100
- Console.error("Failed to audit with learnpack")
101
-
102
- // Si `execSync` lanza un error, capturamos el mensaje de error
103
- if (error instanceof Error) {
104
- Console.error(error.message)
105
- } else {
106
- Console.error("Unknown error occurred")
107
- }
108
-
109
- // Detener la ejecución del comando si `learnpack publish` falla
110
- process.exit(1)
111
- }
112
-
113
- // Continuar con el proceso de build solo si `learnpack publish` fue exitoso
114
- Console.info(
115
- "Learnpack publish completed successfully. Proceeding with build..."
116
- )
117
- }
118
-
119
- type Academy = {
120
- id: number
121
- name: string
122
- slug?: string
123
- timezone?: string
124
- }
125
-
126
- type Category = {
127
- id: number
128
- slug: string
129
- title: string
130
- lang: string
131
- academy: Academy
132
- }
133
-
134
- function getCategoriesByAcademy(
135
- categories: Category[],
136
- academy: Academy
137
- ): Category[] {
138
- return categories.filter((cat) => cat.academy.id === academy.id)
139
- }
140
-
141
- const selectAcademy = async (
142
- academies: TAcademy[],
143
- bcToken: string
144
- ): Promise<{ academy: TAcademy | null; category: number }> => {
145
- if (academies.length === 0) {
146
- return { academy: null, category: 0 }
147
- }
148
-
149
- if (academies.length === 1) {
150
- return { academy: academies[0], category: 0 }
151
- }
152
-
153
- // prompts the user to select an academy to upload the assets
154
- Console.info("In which academy do you want to publish the asset?")
155
- const response = await prompts({
156
- type: "select",
157
- name: "academy",
158
- message: "Select an academy",
159
- choices: academies.map((academy) => ({
160
- title: academy.name,
161
- value: academy,
162
- })),
163
- })
164
-
165
- const categories: Category[] = await api.getCategories(bcToken)
166
- const categoriesByAcademy = getCategoriesByAcademy(
167
- categories,
168
- response.academy
169
- )
170
-
171
- const categoriesPrompt = await prompts({
172
- type: "select",
173
- name: "category",
174
- message: "Select a category",
175
- choices: categoriesByAcademy.map((category) => ({
176
- title: category.title,
177
- value: category.id,
178
- })),
179
- })
180
-
181
- return {
182
- academy: response.academy,
183
- category: categoriesPrompt.category,
184
- }
185
- }
186
-
187
- class BuildCommand extends SessionCommand {
188
- static description =
189
- "Builds the project by copying necessary files and directories into a zip file"
190
-
191
- static flags = {
192
- help: flags.help({ char: "h" }),
193
- strict: flags.boolean({
194
- char: "s",
195
- description: "strict mode",
196
- default: false,
197
- }),
198
- }
199
-
200
- async init() {
201
- const { flags } = this.parse(BuildCommand)
202
- await this.initSession(flags)
203
- }
204
-
205
- async run() {
206
- const buildDir = path.join(process.cwd(), "build")
207
-
208
- const { flags }: { flags: { strict: boolean } } = this.parse(BuildCommand)
209
- const strict = flags.strict
210
- Console.debug("Strict mode: ", strict)
211
- // this.configManager?.clean()
212
-
213
- const configObject = this.configManager?.get()
214
-
215
- let sessionPayload = await SessionManager.getPayload()
216
-
217
- const sessionExists = sessionPayload && sessionPayload.rigobot
218
-
219
- const isValidToken =
220
- sessionExists && sessionPayload.rigobot.key ?
221
- await isValidRigoToken(sessionPayload.rigobot.key) :
222
- false
223
-
224
- const isValidBreathecodeToken =
225
- sessionExists && sessionPayload.token ?
226
- await api.validateToken(sessionPayload.token) :
227
- false
228
-
229
- if (!sessionExists || !isValidBreathecodeToken || !isValidToken) {
230
- Console.info(
231
- "Almost there! First you need to login with 4Geeks.com to use AI Generation tool for creators. You can create a new account here: https://4geeks.com/checkout?plan=learnpack-creator"
232
- )
233
- try {
234
- sessionPayload = await SessionManager.login()
235
- } catch (error) {
236
- Console.error("Error trying to authenticate")
237
- Console.error((error as TypeError).message || (error as string))
238
- }
239
- }
240
-
241
- const rigoToken = sessionPayload.rigobot.key
242
-
243
- const consumable = await getConsumable(
244
- sessionPayload.token,
245
- "learnpack-publish"
246
- )
247
-
248
- if (consumable.count === 0) {
249
- Console.error(
250
- "It seems you cannot publish tutorials. Make sure you creator subscription is up to date here: https://4geeks.com/profile/subscriptions. If you believe there is an issue you can always contact support@4geeks.com"
251
- )
252
- process.exit(1)
253
- }
254
-
255
- if (configObject) {
256
- Console.info("Cleaning configuration files")
257
- this.configManager?.clean()
258
- // build exerises
259
- runAudit(strict)
260
-
261
- Console.debug("Building exercises")
262
- this.configManager?.buildIndex()
263
- }
264
-
265
- const academies = await api.listUserAcademies(sessionPayload.token)
266
-
267
- if (academies.length === 0) {
268
- Console.error(
269
- "It seems you cannot publish tutorials. Make sure you creator subscription is up to date here: https://4geeks.com/profile/subscriptions. If you believe there is an issue you can always contact support@4geeks.com"
270
- )
271
- process.exit(1)
272
- }
273
-
274
- const { academy, category } = await selectAcademy(
275
- academies,
276
- sessionPayload.token
277
- )
278
-
279
- const learnJsonPath = path.join(process.cwd(), "learn.json")
280
- if (!fs.existsSync(learnJsonPath)) {
281
- this.error("learn.json not found")
282
- }
283
-
284
- const learnJson = JSON.parse(fs.readFileSync(learnJsonPath, "utf-8"))
285
-
286
- const zipFilePath = path.join(process.cwd(), `${learnJson.slug}.zip`)
287
-
288
- // Ensure build directory exists
289
- if (!fs.existsSync(buildDir)) {
290
- fs.mkdirSync(buildDir)
291
- }
292
-
293
- if (configObject) {
294
- const { config } = configObject
295
- const appAlreadyExists = checkIfDirectoryExists(`${config?.dirPath}/_app`)
296
-
297
- if (!appAlreadyExists) {
298
- // download app and decompress
299
- await downloadEditor(
300
- config?.editor.version,
301
- `${config?.dirPath}/app.tar.gz`
302
- )
303
-
304
- Console.info("Decompressing LearnPack UI, this may take a minute...")
305
- await decompress(
306
- `${config?.dirPath}/app.tar.gz`,
307
- `${config?.dirPath}/_app/`
308
- )
309
- }
310
- }
311
-
312
- // Copy config.json
313
- const configPath = path.join(process.cwd(), ".learn", "config.json")
314
- if (fs.existsSync(configPath)) {
315
- fs.copyFileSync(configPath, path.join(buildDir, "config.json"))
316
- } else {
317
- this.error("config.json not found")
318
- }
319
-
320
- // Copy .learn/assets directory, if it exists else create it
321
- const assetsDir = path.join(process.cwd(), ".learn", "assets")
322
- if (fs.existsSync(assetsDir)) {
323
- this.copyDirectory(assetsDir, path.join(buildDir, ".learn", "assets"))
324
- } else {
325
- fs.mkdirSync(path.join(buildDir, ".learn", "assets"), {
326
- recursive: true,
327
- })
328
- }
329
-
330
- // Copy .learn/_app directory files to the same level as config.json
331
- const appDir = path.join(process.cwd(), ".learn", "_app")
332
- if (fs.existsSync(appDir)) {
333
- this.copyDirectory(appDir, buildDir)
334
- } else {
335
- this.error(".learn/_app directory not found")
336
- }
337
-
338
- // After copying the _app directory
339
- const indexHtmlPath = path.join(appDir, "index.html")
340
- const buildIndexHtmlPath = path.join(buildDir, "index.html")
341
- const manifestPWA = path.join(appDir, "manifest.webmanifest")
342
- const buildManifestPWA = path.join(buildDir, "manifest.webmanifest")
343
-
344
- if (fs.existsSync(indexHtmlPath)) {
345
- let indexHtmlContent = fs.readFileSync(indexHtmlPath, "utf-8")
346
-
347
- const description = learnJson.description.en || "LearnPack is awesome!"
348
- const title =
349
- learnJson.title.en || "LearnPack: Interactive Learning as a Service"
350
-
351
- const previewUrl =
352
- learnJson.preview ||
353
- "https://raw.githubusercontent.com/learnpack/ide/refs/heads/master/public/learnpack.svg"
354
- // Replace placeholders and the <title>Old title </title> tag for a new tag with the title
355
- indexHtmlContent = indexHtmlContent
356
- .replace(/{{description}}/g, description)
357
- .replace(/<title>.*<\/title>/, `<title>${title}</title>`)
358
- .replace(/{{title}}/g, title)
359
- .replace(/{{preview}}/g, previewUrl)
360
- .replace(/{{slug}}/g, learnJson.slug)
361
- .replace(/{{duration}}/g, minutesToISO8601Duration(learnJson.duration))
362
-
363
- // Write the modified content to the build directory
364
- fs.writeFileSync(buildIndexHtmlPath, indexHtmlContent)
365
- } else {
366
- this.error("index.html not found in _app directory")
367
- }
368
-
369
- if (fs.existsSync(manifestPWA)) {
370
- let manifestPWAContent = fs.readFileSync(manifestPWA, "utf-8")
371
- manifestPWAContent = manifestPWAContent.replace(
372
- "{{course_title}}",
373
- learnJson.title.us
374
- )
375
-
376
- const courseShortName = { answer: "testing-tutorial" }
377
- // const courseShortName = await generateCourseShortName(rigoToken, {
378
- // learnJSON: JSON.stringify(learnJson),
379
- // })
380
-
381
- manifestPWAContent = manifestPWAContent.replace(
382
- "{{course_app_name}}",
383
- courseShortName.answer
384
- )
385
- fs.writeFileSync(buildManifestPWA, manifestPWAContent)
386
- } else {
387
- this.error("manifest.webmanifest not found in _app directory")
388
- }
389
-
390
- // Copy exercises directory
391
- const exercisesDir = path.join(process.cwd(), "exercises")
392
- const learnExercisesDir = path.join(process.cwd(), ".learn", "exercises")
393
-
394
- if (fs.existsSync(exercisesDir)) {
395
- this.copyDirectory(exercisesDir, path.join(buildDir, "exercises"))
396
- } else if (fs.existsSync(learnExercisesDir)) {
397
- this.copyDirectory(learnExercisesDir, path.join(buildDir, "exercises"))
398
- } else {
399
- this.error("exercises directory not found in either location")
400
- }
401
-
402
- fs.copyFileSync(learnJsonPath, path.join(buildDir, "learn.json"))
403
- const sidebarPath = path.join(process.cwd(), ".learn", "sidebar.json")
404
- if (fs.existsSync(sidebarPath)) {
405
- fs.copyFileSync(sidebarPath, path.join(buildDir, "sidebar.json"))
406
- } else {
407
- this.error("sidebar.json not found in .learn directory")
408
- }
409
-
410
- const output = fs.createWriteStream(zipFilePath)
411
- const archive = archiver("zip", {
412
- zlib: { level: 9 },
413
- })
414
-
415
- output.on("close", async () => {
416
- this.log(
417
- `Build completed: ${zipFilePath} (${archive.pointer()} total bytes)`
418
- )
419
- // Remove build directory after zip is created
420
-
421
- Console.debug("Zip file saved in project root")
422
-
423
- const formData = new FormData()
424
- formData.append("file", fs.createReadStream(zipFilePath))
425
- formData.append("config", JSON.stringify(learnJson))
426
-
427
- try {
428
- const res = await axios.post(uploadZipEndpont, formData, {
429
- headers: {
430
- ...formData.getHeaders(),
431
- Authorization: `Token ${rigoToken}`,
432
- },
433
- })
434
- console.log(res.data)
435
-
436
- fs.unlinkSync(zipFilePath)
437
- this.removeDirectory(buildDir)
438
-
439
- await handleAssetCreation(
440
- sessionPayload,
441
- learnJson,
442
- "en",
443
- res.data.url,
444
- "",
445
- []
446
- )
447
- } catch (error) {
448
- if (axios.isAxiosError(error)) {
449
- if (error.response && error.response.status === 403) {
450
- console.error("Error 403:", error.response.data.error)
451
- } else if (error.response && error.response.status === 400) {
452
- console.error(error.response.data.error)
453
- } else {
454
- console.error("Error uploading file:", error)
455
- }
456
- } else {
457
- console.error("Error uploading file:", error)
458
- }
459
-
460
- // fs.unlinkSync(zipFilePath)
461
- // this.removeDirectory(buildDir)
462
- }
463
- })
464
-
465
- archive.on("error", (err: any) => {
466
- throw err
467
- })
468
-
469
- archive.pipe(output)
470
- archive.directory(buildDir, false)
471
- await archive.finalize()
472
- }
473
-
474
- copyDirectory(src: string, dest: string) {
475
- if (!fs.existsSync(dest)) {
476
- fs.mkdirSync(dest, { recursive: true })
477
- }
478
-
479
- const entries = fs.readdirSync(src, { withFileTypes: true })
480
-
481
- for (const entry of entries) {
482
- const srcPath = path.join(src, entry.name)
483
- const destPath = path.join(dest, entry.name)
484
-
485
- if (entry.isDirectory()) {
486
- this.copyDirectory(srcPath, destPath)
487
- } else {
488
- fs.copyFileSync(srcPath, destPath)
489
- }
490
- }
491
- }
492
-
493
- removeDirectory(dir: string) {
494
- if (fs.existsSync(dir)) {
495
- fs.readdirSync(dir).forEach((file) => {
496
- const currentPath = path.join(dir, file)
497
- if (fs.lstatSync(currentPath).isDirectory()) {
498
- this.removeDirectory(currentPath)
499
- } else {
500
- fs.unlinkSync(currentPath)
501
- }
502
- })
503
- fs.rmdirSync(dir)
504
- }
505
- }
506
- }
507
-
508
- BuildCommand.flags = {
509
- strict: flags.boolean({
510
- char: "s",
511
- description: "strict mode",
512
- default: false,
513
- }),
514
- help: flags.help({ char: "h" }),
515
- }
516
-
517
- export default BuildCommand
1
+ /* eslint-disable arrow-parens */
2
+ /* eslint-disable unicorn/no-array-for-each */
3
+ import { execSync } from "child_process"
4
+ import { flags } from "@oclif/command"
5
+ import SessionCommand from "../utils/SessionCommand"
6
+ import SessionManager from "../managers/session"
7
+ import * as fs from "fs"
8
+ import * as path from "path"
9
+ import * as archiver from "archiver"
10
+ import axios from "axios"
11
+ import FormData = require("form-data");
12
+ import Console from "../utils/console"
13
+ import {
14
+ decompress,
15
+ downloadEditor,
16
+ checkIfDirectoryExists,
17
+ } from "../managers/file"
18
+ import api, { getConsumable, RIGOBOT_HOST, TAcademy } from "../utils/api"
19
+ import * as prompts from "prompts"
20
+ import { isValidRigoToken } from "../utils/rigoActions"
21
+ import { minutesToISO8601Duration } from "../utils/misc"
22
+ import { slugify } from "../utils/creatorUtilities"
23
+
24
+ const uploadZipEndpont = RIGOBOT_HOST + "/v1/learnpack/upload"
25
+
26
+ export const handleAssetCreation = async (
27
+ sessionPayload: { token: string; rigobotToken: string },
28
+ learnJson: any,
29
+ selectedLang: string,
30
+ learnpackDeployUrl: string,
31
+ b64IndexReadme: string,
32
+ all_translations: string[] = []
33
+ ) => {
34
+ const category = "uncategorized"
35
+
36
+ try {
37
+ const user = await api.validateToken(sessionPayload.token)
38
+
39
+ let slug = slugify(learnJson.title[selectedLang]).slice(0, 47)
40
+ slug = `${slug}-${selectedLang}`
41
+
42
+ const { exists } = await api.doesAssetExists(sessionPayload.token, slug)
43
+
44
+ if (!exists) {
45
+ Console.info("Asset does not exist in this academy, creating it")
46
+ const asset = await api.createAsset(sessionPayload.token, {
47
+ slug: slug,
48
+ title: learnJson.title[selectedLang],
49
+ lang: selectedLang,
50
+ description: learnJson.description[selectedLang],
51
+ learnpack_deploy_url: learnpackDeployUrl,
52
+ technologies: learnJson.technologies.map((tech: string) =>
53
+ tech.toLowerCase().replace(/\s+/g, "-")
54
+ ),
55
+ url: learnpackDeployUrl,
56
+ category: category,
57
+ owner: user.id,
58
+ author: user.id,
59
+ preview: learnJson.preview,
60
+ readme_raw: b64IndexReadme,
61
+ all_translations,
62
+ })
63
+ try {
64
+ await api.updateRigoPackage(
65
+ sessionPayload.rigobotToken.trim(),
66
+ learnJson.slug,
67
+ {
68
+ asset_id: asset.id,
69
+ }
70
+ )
71
+ } catch (error) {
72
+ Console.error("Error updating Rigo package:", error)
73
+ }
74
+
75
+ Console.info("Asset created with id", asset.id)
76
+ return asset
77
+ }
78
+
79
+ Console.info("Asset exists, updating it")
80
+ const asset = await api.updateAsset(sessionPayload.token, slug, {
81
+ learnpack_deploy_url: learnpackDeployUrl,
82
+ title: learnJson.title[selectedLang],
83
+ category: category,
84
+ description: learnJson.description[selectedLang],
85
+ all_translations,
86
+ })
87
+ try {
88
+ await api.updateRigoPackage(
89
+ sessionPayload.rigobotToken.trim(),
90
+ learnJson.slug,
91
+ {
92
+ asset_id: asset.id,
93
+ }
94
+ )
95
+ } catch (error) {
96
+ Console.error("Error updating Rigo package:", error)
97
+ }
98
+
99
+ Console.info("Asset updated with id", asset.id)
100
+ return asset
101
+ } catch (error) {
102
+ Console.error("Error updating or creating asset:", error)
103
+ return null
104
+ }
105
+ }
106
+
107
+ const runAudit = (strict: boolean) => {
108
+ try {
109
+ Console.info("Running learnpack audit before publishing...")
110
+ execSync(`learnpack audit ${strict ? "--strict" : ""}`, {
111
+ stdio: "inherit",
112
+ })
113
+ } catch (error) {
114
+ Console.error("Failed to audit with learnpack")
115
+
116
+ // Si `execSync` lanza un error, capturamos el mensaje de error
117
+ if (error instanceof Error) {
118
+ Console.error(error.message)
119
+ } else {
120
+ Console.error("Unknown error occurred")
121
+ }
122
+
123
+ // Detener la ejecución del comando si `learnpack publish` falla
124
+ process.exit(1)
125
+ }
126
+
127
+ // Continuar con el proceso de build solo si `learnpack publish` fue exitoso
128
+ Console.info(
129
+ "Learnpack publish completed successfully. Proceeding with build..."
130
+ )
131
+ }
132
+
133
+ type Academy = {
134
+ id: number;
135
+ name: string;
136
+ slug?: string;
137
+ timezone?: string;
138
+ };
139
+
140
+ type Category = {
141
+ id: number;
142
+ slug: string;
143
+ title: string;
144
+ lang: string;
145
+ academy: Academy;
146
+ };
147
+
148
+ function getCategoriesByAcademy(
149
+ categories: Category[],
150
+ academy: Academy
151
+ ): Category[] {
152
+ return categories.filter((cat) => cat.academy.id === academy.id)
153
+ }
154
+
155
+ const selectAcademy = async (
156
+ academies: TAcademy[],
157
+ bcToken: string
158
+ ): Promise<{ academy: TAcademy | null; category: number }> => {
159
+ if (academies.length === 0) {
160
+ return { academy: null, category: 0 }
161
+ }
162
+
163
+ if (academies.length === 1) {
164
+ return { academy: academies[0], category: 0 }
165
+ }
166
+
167
+ // prompts the user to select an academy to upload the assets
168
+ Console.info("In which academy do you want to publish the asset?")
169
+ const response = await prompts({
170
+ type: "select",
171
+ name: "academy",
172
+ message: "Select an academy",
173
+ choices: academies.map((academy) => ({
174
+ title: academy.name,
175
+ value: academy,
176
+ })),
177
+ })
178
+
179
+ const categories: Category[] = await api.getCategories(bcToken)
180
+ const categoriesByAcademy = getCategoriesByAcademy(
181
+ categories,
182
+ response.academy
183
+ )
184
+
185
+ const categoriesPrompt = await prompts({
186
+ type: "select",
187
+ name: "category",
188
+ message: "Select a category",
189
+ choices: categoriesByAcademy.map((category) => ({
190
+ title: category.title,
191
+ value: category.id,
192
+ })),
193
+ })
194
+
195
+ return {
196
+ academy: response.academy,
197
+ category: categoriesPrompt.category,
198
+ }
199
+ }
200
+
201
+ class BuildCommand extends SessionCommand {
202
+ static description =
203
+ "Builds the project by copying necessary files and directories into a zip file"
204
+
205
+ static flags = {
206
+ help: flags.help({ char: "h" }),
207
+ strict: flags.boolean({
208
+ char: "s",
209
+ description: "strict mode",
210
+ default: false,
211
+ }),
212
+ }
213
+
214
+ async init() {
215
+ const { flags } = this.parse(BuildCommand)
216
+ await this.initSession(flags)
217
+ }
218
+
219
+ async run() {
220
+ const buildDir = path.join(process.cwd(), "build")
221
+
222
+ const { flags }: { flags: { strict: boolean } } = this.parse(BuildCommand)
223
+ const strict = flags.strict
224
+ Console.debug("Strict mode: ", strict)
225
+ // this.configManager?.clean()
226
+
227
+ const configObject = this.configManager?.get()
228
+
229
+ let sessionPayload = await SessionManager.getPayload()
230
+
231
+ const sessionExists = sessionPayload && sessionPayload.rigobot
232
+
233
+ const isValidToken =
234
+ sessionExists && sessionPayload.rigobot.key ?
235
+ await isValidRigoToken(sessionPayload.rigobot.key) :
236
+ false
237
+
238
+ const isValidBreathecodeToken =
239
+ sessionExists && sessionPayload.token ?
240
+ await api.validateToken(sessionPayload.token) :
241
+ false
242
+
243
+ if (!sessionExists || !isValidBreathecodeToken || !isValidToken) {
244
+ Console.info(
245
+ "Almost there! First you need to login with 4Geeks.com to use AI Generation tool for creators. You can create a new account here: https://4geeks.com/checkout?plan=learnpack-creator"
246
+ )
247
+ try {
248
+ sessionPayload = await SessionManager.login()
249
+ } catch (error) {
250
+ Console.error("Error trying to authenticate")
251
+ Console.error((error as TypeError).message || (error as string))
252
+ }
253
+ }
254
+
255
+ const rigoToken = sessionPayload.rigobot.key
256
+
257
+ const consumable = await getConsumable(
258
+ sessionPayload.token,
259
+ "learnpack-publish"
260
+ )
261
+
262
+ if (consumable.count === 0) {
263
+ Console.error(
264
+ "It seems you cannot publish tutorials. Make sure you creator subscription is up to date here: https://4geeks.com/profile/subscriptions. If you believe there is an issue you can always contact support@4geeks.com"
265
+ )
266
+ process.exit(1)
267
+ }
268
+
269
+ if (configObject) {
270
+ Console.info("Cleaning configuration files")
271
+ this.configManager?.clean()
272
+ // build exerises
273
+ runAudit(strict)
274
+
275
+ Console.debug("Building exercises")
276
+ this.configManager?.buildIndex()
277
+ }
278
+
279
+ const academies = await api.listUserAcademies(sessionPayload.token)
280
+
281
+ if (academies.length === 0) {
282
+ Console.error(
283
+ "It seems you cannot publish tutorials. Make sure you creator subscription is up to date here: https://4geeks.com/profile/subscriptions. If you believe there is an issue you can always contact support@4geeks.com"
284
+ )
285
+ process.exit(1)
286
+ }
287
+
288
+ const { academy, category } = await selectAcademy(
289
+ academies,
290
+ sessionPayload.token
291
+ )
292
+
293
+ const learnJsonPath = path.join(process.cwd(), "learn.json")
294
+ if (!fs.existsSync(learnJsonPath)) {
295
+ this.error("learn.json not found")
296
+ }
297
+
298
+ const learnJson = JSON.parse(fs.readFileSync(learnJsonPath, "utf-8"))
299
+
300
+ const zipFilePath = path.join(process.cwd(), `${learnJson.slug}.zip`)
301
+
302
+ // Ensure build directory exists
303
+ if (!fs.existsSync(buildDir)) {
304
+ fs.mkdirSync(buildDir)
305
+ }
306
+
307
+ if (configObject) {
308
+ const { config } = configObject
309
+ const appAlreadyExists = checkIfDirectoryExists(
310
+ `${config?.dirPath}/_app`
311
+ )
312
+
313
+ if (!appAlreadyExists) {
314
+ // download app and decompress
315
+ await downloadEditor(
316
+ config?.editor.version,
317
+ `${config?.dirPath}/app.tar.gz`
318
+ )
319
+
320
+ Console.info("Decompressing LearnPack UI, this may take a minute...")
321
+ await decompress(
322
+ `${config?.dirPath}/app.tar.gz`,
323
+ `${config?.dirPath}/_app/`
324
+ )
325
+ }
326
+ }
327
+
328
+ // Copy config.json
329
+ const configPath = path.join(process.cwd(), ".learn", "config.json")
330
+ if (fs.existsSync(configPath)) {
331
+ fs.copyFileSync(configPath, path.join(buildDir, "config.json"))
332
+ } else {
333
+ this.error("config.json not found")
334
+ }
335
+
336
+ // Copy .learn/assets directory, if it exists else create it
337
+ const assetsDir = path.join(process.cwd(), ".learn", "assets")
338
+ if (fs.existsSync(assetsDir)) {
339
+ this.copyDirectory(assetsDir, path.join(buildDir, ".learn", "assets"))
340
+ } else {
341
+ fs.mkdirSync(path.join(buildDir, ".learn", "assets"), {
342
+ recursive: true,
343
+ })
344
+ }
345
+
346
+ // Copy .learn/_app directory files to the same level as config.json
347
+ const appDir = path.join(process.cwd(), ".learn", "_app")
348
+ if (fs.existsSync(appDir)) {
349
+ this.copyDirectory(appDir, buildDir)
350
+ } else {
351
+ this.error(".learn/_app directory not found")
352
+ }
353
+
354
+ // After copying the _app directory
355
+ const indexHtmlPath = path.join(appDir, "index.html")
356
+ const buildIndexHtmlPath = path.join(buildDir, "index.html")
357
+ const manifestPWA = path.join(appDir, "manifest.webmanifest")
358
+ const buildManifestPWA = path.join(buildDir, "manifest.webmanifest")
359
+
360
+ if (fs.existsSync(indexHtmlPath)) {
361
+ let indexHtmlContent = fs.readFileSync(indexHtmlPath, "utf-8")
362
+
363
+ const description = learnJson.description.en || "LearnPack is awesome!"
364
+ const title =
365
+ learnJson.title.en || "LearnPack: Interactive Learning as a Service"
366
+
367
+ const previewUrl =
368
+ learnJson.preview ||
369
+ "https://raw.githubusercontent.com/learnpack/ide/refs/heads/master/public/learnpack.svg"
370
+ // Replace placeholders and the <title>Old title </title> tag for a new tag with the title
371
+ indexHtmlContent = indexHtmlContent
372
+ .replace(/{{description}}/g, description)
373
+ .replace(/<title>.*<\/title>/, `<title>${title}</title>`)
374
+ .replace(/{{title}}/g, title)
375
+ .replace(/{{preview}}/g, previewUrl)
376
+ .replace(/{{slug}}/g, learnJson.slug)
377
+ .replace(/{{duration}}/g, minutesToISO8601Duration(learnJson.duration))
378
+
379
+ // Write the modified content to the build directory
380
+ fs.writeFileSync(buildIndexHtmlPath, indexHtmlContent)
381
+ } else {
382
+ this.error("index.html not found in _app directory")
383
+ }
384
+
385
+ if (fs.existsSync(manifestPWA)) {
386
+ let manifestPWAContent = fs.readFileSync(manifestPWA, "utf-8")
387
+ manifestPWAContent = manifestPWAContent.replace(
388
+ "{{course_title}}",
389
+ learnJson.title.us
390
+ )
391
+
392
+ const courseShortName = { answer: "testing-tutorial" }
393
+ // const courseShortName = await generateCourseShortName(rigoToken, {
394
+ // learnJSON: JSON.stringify(learnJson),
395
+ // })
396
+
397
+ manifestPWAContent = manifestPWAContent.replace(
398
+ "{{course_app_name}}",
399
+ courseShortName.answer
400
+ )
401
+ fs.writeFileSync(buildManifestPWA, manifestPWAContent)
402
+ } else {
403
+ this.error("manifest.webmanifest not found in _app directory")
404
+ }
405
+
406
+ // Copy exercises directory
407
+ const exercisesDir = path.join(process.cwd(), "exercises")
408
+ const learnExercisesDir = path.join(process.cwd(), ".learn", "exercises")
409
+
410
+ if (fs.existsSync(exercisesDir)) {
411
+ this.copyDirectory(exercisesDir, path.join(buildDir, "exercises"))
412
+ } else if (fs.existsSync(learnExercisesDir)) {
413
+ this.copyDirectory(learnExercisesDir, path.join(buildDir, "exercises"))
414
+ } else {
415
+ this.error("exercises directory not found in either location")
416
+ }
417
+
418
+ fs.copyFileSync(learnJsonPath, path.join(buildDir, "learn.json"))
419
+ const sidebarPath = path.join(process.cwd(), ".learn", "sidebar.json")
420
+ if (fs.existsSync(sidebarPath)) {
421
+ fs.copyFileSync(sidebarPath, path.join(buildDir, "sidebar.json"))
422
+ } else {
423
+ this.error("sidebar.json not found in .learn directory")
424
+ }
425
+
426
+ const output = fs.createWriteStream(zipFilePath)
427
+ const archive = archiver("zip", {
428
+ zlib: { level: 9 },
429
+ })
430
+
431
+ output.on("close", async () => {
432
+ this.log(
433
+ `Build completed: ${zipFilePath} (${archive.pointer()} total bytes)`
434
+ )
435
+ // Remove build directory after zip is created
436
+
437
+ Console.debug("Zip file saved in project root")
438
+
439
+ const formData = new FormData()
440
+ formData.append("file", fs.createReadStream(zipFilePath))
441
+ formData.append("config", JSON.stringify(learnJson))
442
+
443
+ try {
444
+ const res = await axios.post(uploadZipEndpont, formData, {
445
+ headers: {
446
+ ...formData.getHeaders(),
447
+ Authorization: `Token ${rigoToken}`,
448
+ },
449
+ })
450
+ console.log(res.data)
451
+
452
+ fs.unlinkSync(zipFilePath)
453
+ this.removeDirectory(buildDir)
454
+
455
+ await handleAssetCreation(
456
+ sessionPayload,
457
+ learnJson,
458
+ "en",
459
+ res.data.url,
460
+ "",
461
+ []
462
+ )
463
+ } catch (error) {
464
+ if (axios.isAxiosError(error)) {
465
+ if (error.response && error.response.status === 403) {
466
+ console.error("Error 403:", error.response.data.error)
467
+ } else if (error.response && error.response.status === 400) {
468
+ console.error(error.response.data.error)
469
+ } else {
470
+ console.error("Error uploading file:", error)
471
+ }
472
+ } else {
473
+ console.error("Error uploading file:", error)
474
+ }
475
+
476
+ // fs.unlinkSync(zipFilePath)
477
+ // this.removeDirectory(buildDir)
478
+ }
479
+ })
480
+
481
+ archive.on("error", (err: any) => {
482
+ throw err
483
+ })
484
+
485
+ archive.pipe(output)
486
+ archive.directory(buildDir, false)
487
+ await archive.finalize()
488
+ }
489
+
490
+ copyDirectory(src: string, dest: string) {
491
+ if (!fs.existsSync(dest)) {
492
+ fs.mkdirSync(dest, { recursive: true })
493
+ }
494
+
495
+ const entries = fs.readdirSync(src, { withFileTypes: true })
496
+
497
+ for (const entry of entries) {
498
+ const srcPath = path.join(src, entry.name)
499
+ const destPath = path.join(dest, entry.name)
500
+
501
+ if (entry.isDirectory()) {
502
+ this.copyDirectory(srcPath, destPath)
503
+ } else {
504
+ fs.copyFileSync(srcPath, destPath)
505
+ }
506
+ }
507
+ }
508
+
509
+ removeDirectory(dir: string) {
510
+ if (fs.existsSync(dir)) {
511
+ fs.readdirSync(dir).forEach((file) => {
512
+ const currentPath = path.join(dir, file)
513
+ if (fs.lstatSync(currentPath).isDirectory()) {
514
+ this.removeDirectory(currentPath)
515
+ } else {
516
+ fs.unlinkSync(currentPath)
517
+ }
518
+ })
519
+ fs.rmdirSync(dir)
520
+ }
521
+ }
522
+ }
523
+
524
+ BuildCommand.flags = {
525
+ strict: flags.boolean({
526
+ char: "s",
527
+ description: "strict mode",
528
+ default: false,
529
+ }),
530
+ help: flags.help({ char: "h" }),
531
+ }
532
+
533
+ export default BuildCommand