@prenta/cli 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +49 -45
  3. package/CHANGELOG.md +13 -0
  4. package/dist/commands/chrome.d.ts.map +1 -1
  5. package/dist/commands/chrome.js +3 -2
  6. package/dist/commands/chrome.js.map +1 -1
  7. package/dist/commands/migrate-media-storage-key.d.ts +3 -0
  8. package/dist/commands/migrate-media-storage-key.d.ts.map +1 -0
  9. package/dist/commands/migrate-media-storage-key.js +45 -0
  10. package/dist/commands/migrate-media-storage-key.js.map +1 -0
  11. package/dist/commands/migrate-meta.js +2 -2
  12. package/dist/commands/migrate-meta.js.map +1 -1
  13. package/dist/commands/migrate-schema.js +2 -2
  14. package/dist/commands/migrate-schema.js.map +1 -1
  15. package/dist/commands/seed.d.ts +25 -0
  16. package/dist/commands/seed.d.ts.map +1 -1
  17. package/dist/commands/seed.js +74 -7
  18. package/dist/commands/seed.js.map +1 -1
  19. package/dist/index.js +2 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/utils/import-typescript.d.ts +19 -1
  22. package/dist/utils/import-typescript.d.ts.map +1 -1
  23. package/dist/utils/import-typescript.js +56 -6
  24. package/dist/utils/import-typescript.js.map +1 -1
  25. package/dist/utils/load-project-config.js +2 -2
  26. package/dist/utils/load-project-config.js.map +1 -1
  27. package/package.json +2 -2
  28. package/src/__tests__/import-typescript-hooks.test.ts +37 -0
  29. package/src/__tests__/import-typescript.test.ts +46 -1
  30. package/src/__tests__/seed-sanitize.test.ts +160 -0
  31. package/src/__tests__/seed.test.ts +4 -0
  32. package/src/commands/chrome.ts +3 -2
  33. package/src/commands/migrate-media-storage-key.ts +56 -0
  34. package/src/commands/migrate-meta.ts +2 -2
  35. package/src/commands/migrate-schema.ts +2 -2
  36. package/src/commands/seed.ts +96 -7
  37. package/src/index.ts +2 -0
  38. package/src/utils/import-typescript.ts +58 -6
  39. package/src/utils/load-project-config.ts +2 -2
@@ -2,7 +2,7 @@ import { Command } from 'commander'
2
2
  import { resolve } from 'node:path'
3
3
  import ora from 'ora'
4
4
  import { connectProjectDatabase } from '../utils/database.js'
5
- import { importProjectTypescript } from '../utils/import-typescript.js'
5
+ import { importProjectTypescript, projectDefaultExport } from '../utils/import-typescript.js'
6
6
  import { loadProjectEnv } from '../utils/load-dotenv.js'
7
7
  import { logger } from '../utils/logger.js'
8
8
 
@@ -19,7 +19,7 @@ async function loadProjectConfig(configPath: string): Promise<void> {
19
19
  default?: unknown
20
20
  config?: unknown
21
21
  }
22
- const config = mod.default ?? mod.config
22
+ const config = projectDefaultExport(mod, 'config')
23
23
  if (config && typeof config === 'object') {
24
24
  setPrentaConfig(config as never)
25
25
  }
@@ -7,7 +7,11 @@ import ora from 'ora'
7
7
  import { logger } from '../utils/logger.js'
8
8
  import { connectProjectDatabase } from '../utils/database.js'
9
9
  import { validateFormSeeds } from '../utils/form-seed.js'
10
- import { importProjectTypescript, toProjectFileUrl } from '../utils/import-typescript.js'
10
+ import {
11
+ importProjectTypescript,
12
+ projectDefaultExport,
13
+ toProjectFileUrl,
14
+ } from '../utils/import-typescript.js'
11
15
 
12
16
  async function confirm(question: string): Promise<boolean> {
13
17
  const rl = createInterface({ input: process.stdin, output: process.stdout })
@@ -350,7 +354,7 @@ async function loadSeedFile(filePath: string): Promise<unknown> {
350
354
  ? await importProjectTypescript(filePath)
351
355
  : await import(toProjectFileUrl(filePath))
352
356
 
353
- return (mod as { default?: unknown; seed?: unknown }).default ?? (mod as { seed?: unknown }).seed
357
+ return projectDefaultExport(mod, 'seed')
354
358
  }
355
359
 
356
360
  async function runSeed(options: SeedOptions): Promise<void> {
@@ -367,6 +371,7 @@ async function runSeed(options: SeedOptions): Promise<void> {
367
371
  try {
368
372
  seededDb = await connectProjectDatabase()
369
373
  const db = seededDb.db
374
+ await loadSeedConfig()
370
375
 
371
376
  if (options.reset) {
372
377
  const yes = await confirm('This will delete ALL existing documents and versions. Continue?')
@@ -423,15 +428,22 @@ export async function ensureSeedAdmin(db: any): Promise<{ id: string }> {
423
428
  return { id: result.userId }
424
429
  }
425
430
 
426
- function sanitizeSeedData(value: unknown, sanitizeHtml: (html: string) => string): unknown {
431
+ /**
432
+ * Sanitise a value whose field type is unknown: every string that looks like
433
+ * it contains a tag goes through the HTML sanitiser. This is a guess from the
434
+ * string's shape, so it damages plain text that merely contains angle brackets
435
+ * (Markdown blockquotes become `&gt;`, `<your-site>` placeholders vanish). Use
436
+ * it only where the schema cannot say what a field holds.
437
+ */
438
+ function sanitizeByShape(value: unknown, sanitizeHtml: (html: string) => string): unknown {
427
439
  if (Array.isArray(value)) {
428
- return value.map((item) => sanitizeSeedData(item, sanitizeHtml))
440
+ return value.map((item) => sanitizeByShape(item, sanitizeHtml))
429
441
  }
430
442
  if (value && typeof value === 'object') {
431
443
  return Object.fromEntries(
432
444
  Object.entries(value as Record<string, unknown>).map(([key, item]) => [
433
445
  key,
434
- sanitizeSeedData(item, sanitizeHtml),
446
+ sanitizeByShape(item, sanitizeHtml),
435
447
  ]),
436
448
  )
437
449
  }
@@ -441,14 +453,91 @@ function sanitizeSeedData(value: unknown, sanitizeHtml: (html: string) => string
441
453
  return value
442
454
  }
443
455
 
456
+ interface SeedSanitizers {
457
+ sanitizeHtml: (html: string) => string
458
+ sanitizeDocumentHtml: (
459
+ data: Record<string, unknown>,
460
+ collection: string,
461
+ options?: { onUnknownSection?: (section: Record<string, unknown>) => unknown },
462
+ ) => Record<string, unknown>
463
+ sanitizeLayoutTree: (layout: unknown) => unknown
464
+ getPrentaConfig: () =>
465
+ | { collections?: Record<string, { fields?: Record<string, unknown> } | undefined> }
466
+ | undefined
467
+ }
468
+
469
+ /**
470
+ * Sanitise a seed document the way an API write does: by field type.
471
+ *
472
+ * Fields the collection declares are handled by cms-core's
473
+ * `sanitizeDocumentHtml`, which sanitises `richText` (and the rich-text slots
474
+ * of `sections`) and leaves `text`, `textarea` and every other plain type
475
+ * exactly as written, so Markdown stored in a `text` field survives seeding.
476
+ * Keys the collection does not declare, and collections with no schema at all
477
+ * (no loadable `prenta.config.ts`, or an ad-hoc collection), keep the older
478
+ * shape-based pass so undeclared HTML is still cleaned before storage.
479
+ */
480
+ export function sanitizeSeedDocumentData(
481
+ data: Record<string, unknown>,
482
+ collection: string,
483
+ core: SeedSanitizers,
484
+ ): Record<string, unknown> {
485
+ const fields = core.getPrentaConfig?.()?.collections?.[collection]?.fields
486
+ // An installed @prenta/core older than the one that exports the schema-aware
487
+ // sanitiser gets the shape-based pass too.
488
+ const schemaAware =
489
+ typeof core.sanitizeDocumentHtml === 'function' && typeof core.sanitizeLayoutTree === 'function'
490
+ if (!schemaAware || !fields || Array.isArray(fields) || Object.keys(fields).length === 0) {
491
+ return sanitizeByShape(data, core.sanitizeHtml) as Record<string, unknown>
492
+ }
493
+ // The seed does not validate section types and has no registry entries for a
494
+ // project's custom ones, so a section the registry does not know keeps the
495
+ // shape-based pass rather than being stored unsanitised.
496
+ const bySchema = core.sanitizeDocumentHtml(data, collection, {
497
+ onUnknownSection: (section) => sanitizeByShape(section, core.sanitizeHtml),
498
+ })
499
+ const out: Record<string, unknown> = {}
500
+ for (const [key, value] of Object.entries(bySchema)) {
501
+ if (Object.hasOwn(fields, key) || key === 'sections') out[key] = value
502
+ else if (key === '_layout') out[key] = core.sanitizeLayoutTree(value)
503
+ else out[key] = sanitizeByShape(value, core.sanitizeHtml)
504
+ }
505
+ return out
506
+ }
507
+
508
+ /**
509
+ * Register the project's `prenta.config.ts` so the seed can sanitise by field
510
+ * type. A project without a loadable config still seeds; it falls back to the
511
+ * shape-based pass, and says so.
512
+ */
513
+ async function loadSeedConfig(configPath = 'prenta.config.ts'): Promise<void> {
514
+ try {
515
+ const { getPrentaConfig, setPrentaConfig } = await import('@prenta/core')
516
+ if (getPrentaConfig()) return
517
+ if (!existsSync(configPath)) return
518
+ const mod = (await importProjectTypescript(path.resolve(configPath))) as {
519
+ default?: unknown
520
+ config?: unknown
521
+ }
522
+ const config = projectDefaultExport(mod, 'config')
523
+ if (config && typeof config === 'object') setPrentaConfig(config as never)
524
+ } catch (err) {
525
+ const message = err instanceof Error ? err.message : String(err)
526
+ logger.warn(
527
+ `Could not load ${configPath} (${message}). Field types are unknown, so every seed string that looks like HTML will be sanitised, including Markdown in plain-text fields.`,
528
+ )
529
+ }
530
+ }
531
+
444
532
  export async function createSeedDocument(
445
533
  db: any,
446
534
  userId: string,
447
535
  doc: NormalizedSeedDocument,
448
536
  options: { upsert?: boolean } = {},
449
537
  ): Promise<'created' | 'updated'> {
450
- const { extractPlainText, hashContent, sanitizeHtml } = await import('@prenta/core')
451
- const data = sanitizeSeedData(doc.data, sanitizeHtml) as Record<string, unknown>
538
+ const core = await import('@prenta/core')
539
+ const { extractPlainText, hashContent } = core
540
+ const data = sanitizeSeedDocumentData(doc.data, doc.collection, core as SeedSanitizers)
452
541
  const serialized = JSON.stringify(data)
453
542
  const plainText = extractPlainText(serialized)
454
543
  const contentHash = await hashContent(serialized)
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import { registerMigrateMetaCommand } from './commands/migrate-meta.js'
8
8
  import { registerMigrateMediaUsageCommand } from './commands/migrate-media-usage.js'
9
9
  import { registerMigrateMediaOptimizeCommand } from './commands/migrate-media-optimize.js'
10
10
  import { registerMigrateContentHashCommand } from './commands/migrate-content-hash.js'
11
+ import { registerMigrateMediaStorageKeyCommand } from './commands/migrate-media-storage-key.js'
11
12
  import { registerGenerateCommand } from './commands/generate.js'
12
13
  import { registerSeedCommand } from './commands/seed.js'
13
14
  import { registerImportCommand } from './commands/import.js'
@@ -50,6 +51,7 @@ registerMigrateMetaCommand(program)
50
51
  registerMigrateMediaUsageCommand(program)
51
52
  registerMigrateMediaOptimizeCommand(program)
52
53
  registerMigrateContentHashCommand(program)
54
+ registerMigrateMediaStorageKeyCommand(program)
53
55
  registerGenerateCommand(program)
54
56
  registerSeedCommand(program)
55
57
  registerImportCommand(program)
@@ -15,18 +15,70 @@ export function toProjectFileUrl(filePath: string): string {
15
15
  return pathToFileURL(path.resolve(filePath)).href
16
16
  }
17
17
 
18
+ /**
19
+ * Install tsx's process-wide hooks once: the ESM loader and the CommonJS
20
+ * `require` hook.
21
+ *
22
+ * Both are needed. A scaffolded project has no `"type": "module"`, so Node
23
+ * classifies its `.ts` files as CommonJS. The ESM loader compiles the entry
24
+ * file (`generated/prisma/client.ts`), but that file's own imports then run as
25
+ * `require('./internal/class')`, and on Node 22 only the CommonJS hook can
26
+ * resolve an extensionless TypeScript sibling. Without it every command that
27
+ * opens the project database fails with "Cannot find module './internal/class'".
28
+ */
29
+ async function registerTsx(): Promise<void> {
30
+ if (registered) return
31
+ const [esm, cjs] = await Promise.all([import('tsx/esm/api'), import('tsx/cjs/api')])
32
+ esm.register()
33
+ cjs.register()
34
+ registered = true
35
+ }
36
+
37
+ /**
38
+ * The exports a loaded project module actually declared.
39
+ *
40
+ * A scaffolded project has no `"type": "module"`, so tsx compiles its
41
+ * TypeScript to CommonJS: `export default config` and `export const header`
42
+ * become `module.exports = { __esModule: true, default: config, header }`.
43
+ * Imported from this ESM CLI, that whole object arrives as the namespace's
44
+ * `default`, one level above what the file exported. Reading the namespace
45
+ * directly therefore finds `{ default: config }` where the config should be
46
+ * (an object with no collections, plugins or storage) and no named exports at
47
+ * all, so every command that loaded `prenta.config.ts` ran as if it were empty.
48
+ */
49
+ export function projectModuleExports(mod: unknown): Record<string, unknown> {
50
+ if (!mod || typeof mod !== 'object') return {}
51
+ const namespace = mod as Record<string, unknown>
52
+ const outer = namespace.default
53
+ if (
54
+ outer &&
55
+ typeof outer === 'object' &&
56
+ !Array.isArray(outer) &&
57
+ (outer as Record<string, unknown>).__esModule === true
58
+ ) {
59
+ return outer as Record<string, unknown>
60
+ }
61
+ return namespace
62
+ }
63
+
64
+ /**
65
+ * The default export of a loaded project module, or the named export
66
+ * `fallbackName` when the file has no default.
67
+ */
68
+ export function projectDefaultExport(mod: unknown, fallbackName?: string): unknown {
69
+ const exported = projectModuleExports(mod)
70
+ if (exported.default !== undefined) return exported.default
71
+ return fallbackName ? exported[fallbackName] : undefined
72
+ }
73
+
18
74
  /**
19
75
  * Load a consumer TypeScript file (prenta.config.ts, lib/prisma.ts,
20
- * generated/prisma/client.ts) via tsx's process-wide ESM hook.
76
+ * generated/prisma/client.ts) via tsx's process-wide hooks.
21
77
  *
22
78
  * Do not use `tsImport()` — its namespaced loader is what produced the
23
79
  * Windows `?namespace=` crashes on adapter-pg and then enums.ts.
24
80
  */
25
81
  export async function importProjectTypescript(filePath: string): Promise<unknown> {
26
- if (!registered) {
27
- const { register } = await import('tsx/esm/api')
28
- register()
29
- registered = true
30
- }
82
+ await registerTsx()
31
83
  return import(toProjectFileUrl(filePath))
32
84
  }
@@ -1,5 +1,5 @@
1
1
  import { resolve } from 'node:path'
2
- import { importProjectTypescript } from './import-typescript.js'
2
+ import { importProjectTypescript, projectDefaultExport } from './import-typescript.js'
3
3
  import { logger } from './logger.js'
4
4
 
5
5
  /**
@@ -15,7 +15,7 @@ export async function loadProjectConfig(configPath: string): Promise<void> {
15
15
  default?: unknown
16
16
  config?: unknown
17
17
  }
18
- const config = mod.default ?? mod.config
18
+ const config = projectDefaultExport(mod, 'config')
19
19
  if (!config || typeof config !== 'object') return
20
20
  setPrentaConfig(config as never)
21
21