qarpeo 0.1.0 → 0.1.2

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.
@@ -431,6 +431,9 @@ function resolveProjectName(nuxt, options) {
431
431
  if (siteConfig.name) return siteConfig.name;
432
432
  if (process.env.CLOUDFLARE_PROJECT_NAME) return process.env.CLOUDFLARE_PROJECT_NAME;
433
433
  if (process.env.WRANGLER_NAME) return process.env.WRANGLER_NAME;
434
+ if (process.env.QARPEO_WORKER_NAME) return process.env.QARPEO_WORKER_NAME;
435
+ if (process.env.WORKER_NAME) return process.env.WORKER_NAME;
436
+ if (process.env.CF_WORKER_NAME) return process.env.CF_WORKER_NAME;
434
437
  try {
435
438
  const pkgPath = resolve(nuxt.options.rootDir, "package.json");
436
439
  if (existsSync(pkgPath)) {
package/dist/module.d.ts CHANGED
@@ -10,6 +10,7 @@ export { generateAuthSchema, getActiveAuthTableNames } from "./utils/auth-schema
10
10
  export { cmsCollections, cmsEntries, cmsRevisions, ALL_CMS_TABLE_NAMES, getActiveCmsTableNames, } from "./utils/cms-schema";
11
11
  export { generatePaymentsSchema, getActivePaymentsTableNames } from "./utils/payments-schema";
12
12
  export { generateNotificationsSchema, getActiveNotificationsTableNames } from "./utils/notifications-schema";
13
+ export { scanContentEntries } from "./utils/cms-scan";
13
14
  export { generateTenantsSchema, getActiveTenantsTableNames } from "./utils/tenants-schema";
14
15
  export { resolveAllCmsSources, discoverSources, resolveSourcePrefix, isRemoteSource, matchesSourceFilters, matchesGlobFilter, stripOrderPrefix, extractOrderPrefix, isGroupSegment, extractGroupTitle, matchPathPatterns, resolveCollectionForPath, } from "./utils/cms-sources";
15
16
  declare const module: NuxtModule<ModuleOptions>;
package/dist/module.mjs CHANGED
@@ -9,6 +9,9 @@ import { generateAuthSchema } from './chunks/auth-schema.mjs';
9
9
  export { getActiveAuthTableNames } from './chunks/auth-schema.mjs';
10
10
  import { createHash } from 'node:crypto';
11
11
  import { readdir, readFile } from 'node:fs/promises';
12
+ import { parseMarkdown } from 'comark';
13
+ import { render } from 'comark/render';
14
+ import { parse } from 'yaml';
12
15
  import { downloadTemplate } from 'giget';
13
16
  import { snakeCase, integer, text, index } from 'drizzle-orm/sqlite-core';
14
17
  import 'node:child_process';
@@ -16,7 +19,7 @@ import 'drizzle-orm/node-sqlite';
16
19
  import 'node:process';
17
20
  import 'node:readline/promises';
18
21
 
19
- const version = "0.1.0";
22
+ const version = "0.1.2";
20
23
 
21
24
  function ensureDevEnv(rootDir) {
22
25
  const envPath = join(rootDir, ".env");
@@ -179,6 +182,10 @@ function resolveCollectionForPath(entryPath, collectionsConfig, fallbackId = "co
179
182
  return colId;
180
183
  }
181
184
  }
185
+ const firstSegment = entryPath.split("/").filter(Boolean)[0];
186
+ if (firstSegment && collectionsConfig[firstSegment]) {
187
+ return firstSegment;
188
+ }
182
189
  }
183
190
  return fallbackId;
184
191
  }
@@ -349,6 +356,244 @@ async function resolveAllCmsSources(options) {
349
356
  return resolvedList;
350
357
  }
351
358
 
359
+ function slugifyHeading(text) {
360
+ return text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-");
361
+ }
362
+ function extractTOC(md) {
363
+ const lines = md.split("\n");
364
+ const flat = [];
365
+ for (const line of lines) {
366
+ const m = line.match(/^(#{2,6})\s+(.+)/);
367
+ if (!m) continue;
368
+ const depth = m[1].length;
369
+ const rawText = m[2].trim().replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/[`*_~]/g, "");
370
+ flat.push({ id: slugifyHeading(rawText), text: rawText, depth });
371
+ }
372
+ const result = [];
373
+ let current2 = null;
374
+ for (const item of flat) {
375
+ if (item.depth === 2) {
376
+ current2 = { ...item, children: [] };
377
+ result.push(current2);
378
+ } else if (item.depth === 3 && current2) {
379
+ current2.children.push(item);
380
+ }
381
+ }
382
+ return result;
383
+ }
384
+ function parseFrontmatter(raw) {
385
+ const clean = raw ? raw.replace(/^\uFEFF/, "") : "";
386
+ const fmMatch = clean.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)/);
387
+ if (!fmMatch) return { data: {}, content: clean };
388
+ try {
389
+ const parsed = parse(fmMatch[1] || "");
390
+ return {
391
+ data: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {},
392
+ content: fmMatch[2] || ""
393
+ };
394
+ } catch {
395
+ return { data: {}, content: clean };
396
+ }
397
+ }
398
+ function computeContentHash(text) {
399
+ return createHash("sha256").update(text).digest("hex");
400
+ }
401
+ async function readNavJson(dir) {
402
+ const navJsonPath = `${dir}/.navigation.json`;
403
+ if (existsSync(navJsonPath)) {
404
+ try {
405
+ const raw = await readFile(navJsonPath, "utf8");
406
+ const clean = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
407
+ return JSON.parse(clean);
408
+ } catch {
409
+ }
410
+ }
411
+ const navYmlPath = `${dir}/.navigation.yml`;
412
+ if (existsSync(navYmlPath)) {
413
+ try {
414
+ const raw = await readFile(navYmlPath, "utf8");
415
+ return parse(raw) || {};
416
+ } catch {
417
+ }
418
+ }
419
+ return {};
420
+ }
421
+ async function scanContentEntries(options) {
422
+ const { contentDir, collectionsConfig = {}, sources = [], exclude } = options;
423
+ const entries = [];
424
+ const now = Date.now();
425
+ async function syncSource(source) {
426
+ if (!source?.resolvedDir || !existsSync(source.resolvedDir)) return;
427
+ let orderCounter = 0;
428
+ const processDir = async (dir, relBase, sectionNavMeta) => {
429
+ let dirItems;
430
+ try {
431
+ dirItems = await readdir(dir, { withFileTypes: true });
432
+ } catch {
433
+ return;
434
+ }
435
+ dirItems.sort(
436
+ (a, b) => a.name.localeCompare(b.name, void 0, { numeric: true })
437
+ );
438
+ const navMeta = await readNavJson(dir);
439
+ if (navMeta.private === true || navMeta.draft === true || navMeta.exclude === true) {
440
+ return;
441
+ }
442
+ const isTopLevelSection = Boolean(relBase && !relBase.includes("/"));
443
+ const currentSectionNavMeta = sectionNavMeta || (isTopLevelSection ? {
444
+ title: navMeta.title || stripOrderPrefix(relBase).charAt(0).toUpperCase() + stripOrderPrefix(relBase).slice(1).replace(/-/g, " "),
445
+ icon: navMeta.icon,
446
+ order: navMeta.order ?? extractOrderPrefix(relBase),
447
+ navigation: navMeta.navigation,
448
+ hidden: navMeta.hidden
449
+ } : void 0);
450
+ for (const item of dirItems) {
451
+ if (item.name.startsWith(".") || item.name.startsWith("_")) continue;
452
+ const subRel = relBase ? `${relBase}/${item.name}` : item.name;
453
+ if (item.isDirectory()) {
454
+ await processDir(`${dir}/${item.name}`, subRel, currentSectionNavMeta);
455
+ } else if (item.isFile() && item.name.endsWith(".md")) {
456
+ const combinedExclude = [
457
+ ...Array.isArray(exclude) ? exclude : exclude ? [exclude] : [],
458
+ ...Array.isArray(source.exclude) ? source.exclude : source.exclude ? [source.exclude] : []
459
+ ];
460
+ if (!matchesSourceFilters(subRel, source.include, combinedExclude)) continue;
461
+ const filePath = `${dir}/${item.name}`;
462
+ let rawContent = "";
463
+ try {
464
+ rawContent = await readFile(filePath, "utf8");
465
+ } catch {
466
+ continue;
467
+ }
468
+ const fileHash = computeContentHash(rawContent);
469
+ const { data: fm, content: body } = parseFrontmatter(rawContent);
470
+ const rawRelSegments = subRel.replace(/\.md$/, "").split("/").filter(Boolean);
471
+ const isReadme = item.name.toLowerCase() === "readme.md";
472
+ const isIndex = item.name.replace(/\.md$/, "") === "index" || item.name.replace(/\.md$/, "") === "01.index" || isReadme;
473
+ const groupSegment = rawRelSegments.slice(0, -1).find(isGroupSegment);
474
+ let groupMeta;
475
+ if (groupSegment) {
476
+ const groupOrder = extractOrderPrefix(groupSegment);
477
+ const defaultGroupTitle = extractGroupTitle(groupSegment);
478
+ const groupKey = stripOrderPrefix(groupSegment).replace(/^\(|\)$/g, "");
479
+ const currentDirName = dir.replace(/\\/g, "/").split("/").filter(Boolean).pop();
480
+ const isGroupDir = currentDirName === groupSegment;
481
+ groupMeta = {
482
+ key: groupKey,
483
+ title: isGroupDir && navMeta.title ? navMeta.title : defaultGroupTitle,
484
+ icon: isGroupDir && navMeta.icon ? navMeta.icon : void 0,
485
+ order: groupOrder
486
+ };
487
+ }
488
+ const cleanedRelSegments = rawRelSegments.filter((seg) => !isGroupSegment(seg)).map(stripOrderPrefix).filter(Boolean);
489
+ if (isIndex && cleanedRelSegments.length > 0) {
490
+ cleanedRelSegments.pop();
491
+ }
492
+ const prefixSegments = (source.normalizedPrefix || "/").split("/").filter(Boolean);
493
+ const combinedSegments = [...prefixSegments, ...cleanedRelSegments];
494
+ const entryPath = "/" + combinedSegments.join("/");
495
+ const defaultCollectionId = prefixSegments[0] || "content";
496
+ const collectionId = resolveCollectionForPath(
497
+ entryPath,
498
+ collectionsConfig,
499
+ defaultCollectionId
500
+ );
501
+ const slug = fm.slug || cleanedRelSegments[cleanedRelSegments.length - 1] || prefixSegments[prefixSegments.length - 1] || "index";
502
+ const title = fm.title || slug;
503
+ const toc = extractTOC(body);
504
+ let ast = { nodes: [], frontmatter: {}, meta: {} };
505
+ let contentHtml = "";
506
+ try {
507
+ ast = await parseMarkdown(body);
508
+ contentHtml = (await render(ast, { format: "text/html" })).trim();
509
+ } catch {
510
+ contentHtml = body;
511
+ }
512
+ const description = fm.description || null;
513
+ const coverImage = fm.coverImage || fm.cover_image || null;
514
+ const tags = Array.isArray(fm.tags) ? fm.tags.join(",") : fm.tags || null;
515
+ const folderNum = rawRelSegments.length > 1 ? extractOrderPrefix(rawRelSegments[0]) : void 0;
516
+ const effectiveFolderNum = folderNum ?? (typeof currentSectionNavMeta?.order === "number" ? currentSectionNavMeta.order : void 0);
517
+ const folderOrder = effectiveFolderNum != null ? effectiveFolderNum * 1e3 : 5e4;
518
+ let subfolderOffset = 0;
519
+ if (rawRelSegments.length > 2) {
520
+ const subDir = rawRelSegments[1];
521
+ const subDirNum = extractOrderPrefix(subDir);
522
+ const subOrder = subDirNum ?? (typeof groupMeta?.order === "number" ? groupMeta.order : typeof navMeta?.order === "number" ? navMeta.order : void 0);
523
+ subfolderOffset = 500 + (subOrder != null ? subOrder * 50 : 100);
524
+ }
525
+ const fileNum = extractOrderPrefix(item.name);
526
+ const itemOrder = typeof fm.order === "number" ? fm.order : isIndex ? 0 : fileNum != null ? fileNum : 100 + orderCounter++;
527
+ const groupOrderOffset = typeof groupMeta?.order === "number" ? groupMeta.order * 100 : 0;
528
+ const finalOrder = folderOrder + subfolderOffset + groupOrderOffset + itemOrder;
529
+ const itemTitle = fm.title || (isIndex ? navMeta.title || title : title);
530
+ const effectiveSection = currentSectionNavMeta?.title ? { title: currentSectionNavMeta.title, icon: currentSectionNavMeta.icon } : navMeta.title ? { title: navMeta.title, icon: navMeta.icon } : void 0;
531
+ const isDraft = Boolean(
532
+ fm.draft === true || fm.private === true || fm.status === "draft" || navMeta.draft === true || navMeta.private === true
533
+ );
534
+ const entryStatus = isDraft ? "draft" : "published";
535
+ const metadataJson = JSON.stringify({
536
+ ...fm,
537
+ navigation: fm.navigation,
538
+ hidden: fm.hidden,
539
+ draft: isDraft,
540
+ _ast: ast,
541
+ _toc: { links: toc },
542
+ _nav: navMeta,
543
+ _section: effectiveSection,
544
+ _sectionOrder: effectiveFolderNum,
545
+ _group: groupMeta,
546
+ _itemTitle: itemTitle,
547
+ _isIndex: isIndex,
548
+ _source: source.from || "unknown",
549
+ _sourceLabel: source.label || source.from || "source",
550
+ _sourcePriority: source.priority ?? 0,
551
+ _sourceOrder: source.order ?? 0
552
+ });
553
+ entries.push({
554
+ collection_id: collectionId,
555
+ slug,
556
+ path: entryPath,
557
+ title,
558
+ description,
559
+ cover_image: coverImage,
560
+ tags,
561
+ order: finalOrder,
562
+ content_md: body,
563
+ content_html: contentHtml,
564
+ metadata_json: metadataJson,
565
+ status: entryStatus,
566
+ source: "file",
567
+ file_path: filePath,
568
+ content_hash: fileHash,
569
+ published_at: isDraft ? null : now,
570
+ created_at: now,
571
+ updated_at: now
572
+ });
573
+ }
574
+ }
575
+ };
576
+ await processDir(source.resolvedDir, "");
577
+ }
578
+ const lowPrioritySources = (sources || []).filter((s) => (s.priority ?? 0) < 10);
579
+ const highPrioritySources = (sources || []).filter((s) => (s.priority ?? 0) >= 10);
580
+ for (const src of lowPrioritySources) {
581
+ await syncSource(src);
582
+ }
583
+ if (existsSync(contentDir)) {
584
+ await syncSource({
585
+ from: "content",
586
+ resolvedDir: contentDir,
587
+ normalizedPrefix: "/",
588
+ priority: 10
589
+ });
590
+ }
591
+ for (const src of highPrioritySources) {
592
+ await syncSource(src);
593
+ }
594
+ return entries;
595
+ }
596
+
352
597
  const ALL_PAYMENTS_TABLE_NAMES = [
353
598
  "_qarpeo_customers",
354
599
  "_qarpeo_subscriptions",
@@ -1336,6 +1581,12 @@ export default queueHandler;
1336
1581
  "./runtime/server/utils/schema-fallback"
1337
1582
  );
1338
1583
  }
1584
+ const cmsManifestFallbackTemplate = addTemplate({
1585
+ filename: "qarpeo/cms-manifest-fallback.mjs",
1586
+ write: true,
1587
+ getContents: () => "export const manifestEntries = [];\nexport const manifestCollections = {};\n"
1588
+ });
1589
+ nuxt.options.alias["#qarpeo/cms/manifest"] = cmsManifestFallbackTemplate.dst;
1339
1590
  if (options.payments) {
1340
1591
  const paymentsSchemaTemplate = addTemplate({
1341
1592
  filename: "qarpeo/payments-schema.ts",
@@ -1705,15 +1956,16 @@ export default queueHandler;
1705
1956
  const kvBinding = resolveBindingName("kv");
1706
1957
  nitroConfig.cloudflare.wrangler.kv_namespaces = nitroConfig.cloudflare.wrangler.kv_namespaces || [];
1707
1958
  if (!nitroConfig.cloudflare.wrangler.kv_namespaces.some((ns) => ns.binding === kvBinding)) {
1959
+ const kvId = process.env.QARPEO_KV_ID || process.env.KV_ID || `${kvBinding}_LOCAL_DEV`;
1708
1960
  nitroConfig.cloudflare.wrangler.kv_namespaces.push({
1709
1961
  binding: kvBinding,
1710
- id: `${kvBinding}_LOCAL_DEV`
1962
+ id: kvId
1711
1963
  });
1712
1964
  }
1713
1965
  }
1714
1966
  if (options.blob || options.r2) {
1715
1967
  const blobBinding = resolveBindingName("blob");
1716
- const bucketName = `${blobBinding.toLowerCase().replace(/[^a-z0-9-]/g, "-")}-prod`;
1968
+ const bucketName = process.env.QARPEO_BLOB_BUCKET || process.env.BLOB_NAME || process.env.BUCKET_NAME || `${blobBinding.toLowerCase().replace(/[^a-z0-9-]/g, "-")}-prod`;
1717
1969
  nitroConfig.cloudflare.wrangler.r2_buckets = nitroConfig.cloudflare.wrangler.r2_buckets || [];
1718
1970
  if (!nitroConfig.cloudflare.wrangler.r2_buckets.some((b) => b.binding === blobBinding)) {
1719
1971
  nitroConfig.cloudflare.wrangler.r2_buckets.push({
@@ -1726,10 +1978,12 @@ export default queueHandler;
1726
1978
  const dbBinding = resolveBindingName("db", void 0);
1727
1979
  nitroConfig.cloudflare.wrangler.d1_databases = nitroConfig.cloudflare.wrangler.d1_databases || [];
1728
1980
  if (!nitroConfig.cloudflare.wrangler.d1_databases.some((d) => d.binding === dbBinding)) {
1981
+ const dbId = typeof options.db === "object" && options.db.databaseId || process.env.QARPEO_DB_ID || process.env.DATABASE_ID || process.env.DB_ID || `${dbBinding}_PROD`;
1982
+ const dbName = typeof options.db === "object" && options.db.databaseName || process.env.QARPEO_DB_NAME || process.env.DB_NAME || dbBinding;
1729
1983
  nitroConfig.cloudflare.wrangler.d1_databases.push({
1730
1984
  binding: dbBinding,
1731
- database_name: `${dbBinding}_PROD`,
1732
- database_id: `${dbBinding}_PROD`
1985
+ database_name: dbName,
1986
+ database_id: dbId
1733
1987
  });
1734
1988
  }
1735
1989
  if (isDrizzle && schemaTemplateDst) {
@@ -1753,6 +2007,10 @@ export default queueHandler;
1753
2007
  nitroConfig.alias["#qarpeo/queue-consumer"] = queueConsumer;
1754
2008
  }
1755
2009
  }
2010
+ if (nuxt.options.alias["#qarpeo/cms/manifest"]) {
2011
+ nitroConfig.alias = nitroConfig.alias || {};
2012
+ nitroConfig.alias["#qarpeo/cms/manifest"] = nuxt.options.alias["#qarpeo/cms/manifest"];
2013
+ }
1756
2014
  if (hasNuxtModule("@nuxt/content")) {
1757
2015
  nitroConfig.runtimeConfig = nitroConfig.runtimeConfig || {};
1758
2016
  nitroConfig.runtimeConfig.content = nitroConfig.runtimeConfig.content || {};
@@ -3037,6 +3295,33 @@ export default queueHandler;
3037
3295
  ])
3038
3296
  )
3039
3297
  };
3298
+ const cmsManifestTemplate = addTemplate({
3299
+ filename: "qarpeo/cms-manifest.mjs",
3300
+ write: true,
3301
+ async getContents() {
3302
+ try {
3303
+ const entries = await scanContentEntries({
3304
+ contentDir: resolvedContentDir,
3305
+ collectionsConfig: cmsConfig.collections,
3306
+ sources: resolvedSources,
3307
+ exclude: cmsConfig.exclude
3308
+ });
3309
+ return `export const manifestEntries = ${JSON.stringify(entries)};
3310
+ export const manifestCollections = ${JSON.stringify(cmsConfig.collections || {})};
3311
+ `;
3312
+ } catch (err) {
3313
+ console.warn("[qarpeo:cms] Error scanning CMS manifest at build time:", err);
3314
+ return `export const manifestEntries = [];
3315
+ export const manifestCollections = ${JSON.stringify(cmsConfig.collections || {})};
3316
+ `;
3317
+ }
3318
+ }
3319
+ });
3320
+ nuxt.options.alias["#qarpeo/cms/manifest"] = cmsManifestTemplate.dst;
3321
+ nuxt.hook("nitro:config", (nitroConfig) => {
3322
+ nitroConfig.alias = nitroConfig.alias || {};
3323
+ nitroConfig.alias["#qarpeo/cms/manifest"] = cmsManifestTemplate.dst;
3324
+ });
3040
3325
  addNitroPlugin(resolver.resolve("./runtime/server/plugins/cms"));
3041
3326
  addServerHandler({
3042
3327
  route: `${cmsApiPath}/collections`,
@@ -4433,4 +4718,4 @@ export default queueHandler;
4433
4718
  }
4434
4719
  });
4435
4720
 
4436
- export { ALL_CMS_TABLE_NAMES, checkDrizzleVersion, cmsCollections, cmsEntries, cmsRevisions, createWranglerConfig, module$1 as default, discoverSources, extractGroupTitle, extractOrderPrefix, findAgentFiles, findJobFiles, findQueueFiles, findSchemaFiles, generateAuthSchema, generateDevWranglerConfig, generateNotificationsSchema, generatePaymentsSchema, generateTenantsSchema, getActiveCmsTableNames, getActiveNotificationsTableNames, getActivePaymentsTableNames, getActiveTenantsTableNames, isGroupSegment, isRemoteSource, matchPathPatterns, matchesGlobFilter, matchesSourceFilters, resolveAllCmsSources, resolveCollectionForPath, resolveProjectName, resolveSourcePrefix, scanSchemaExports, stripOrderPrefix };
4721
+ export { ALL_CMS_TABLE_NAMES, checkDrizzleVersion, cmsCollections, cmsEntries, cmsRevisions, createWranglerConfig, module$1 as default, discoverSources, extractGroupTitle, extractOrderPrefix, findAgentFiles, findJobFiles, findQueueFiles, findSchemaFiles, generateAuthSchema, generateDevWranglerConfig, generateNotificationsSchema, generatePaymentsSchema, generateTenantsSchema, getActiveCmsTableNames, getActiveNotificationsTableNames, getActivePaymentsTableNames, getActiveTenantsTableNames, isGroupSegment, isRemoteSource, matchPathPatterns, matchesGlobFilter, matchesSourceFilters, resolveAllCmsSources, resolveCollectionForPath, resolveProjectName, resolveSourcePrefix, scanContentEntries, scanSchemaExports, stripOrderPrefix };
@@ -175,8 +175,8 @@ const collectionMode = computed<string>(() => {
175
175
  return collectionConfig.value.mode || currentCollection.value?.mode || "db"
176
176
  })
177
177
 
178
- const isFileLocked = computed(() => collectionMode.value === "file-lock")
179
- const isGitSync = computed(() => collectionMode.value === "git-sync")
178
+ const isFileLocked = computed(() => collectionMode.value === "file")
179
+ const isGitSync = computed(() => collectionMode.value === "hybrid")
180
180
 
181
181
  const activeApproval = computed(() => {
182
182
  return collectionConfig.value.approval
@@ -1318,7 +1318,7 @@ onMounted(() => {
1318
1318
  </UBadge>
1319
1319
  <UBadge
1320
1320
  v-if="currentView === 'editor' && isGitSync"
1321
- label="🌿 Git-sync active"
1321
+ label="⚡ Hybrid mode active"
1322
1322
  size="xs"
1323
1323
  color="success"
1324
1324
  variant="subtle"
@@ -1474,7 +1474,7 @@ onMounted(() => {
1474
1474
  </template>
1475
1475
  </template>
1476
1476
  <UBadge v-else color="warning" variant="subtle">
1477
- 🔒 File-locked — edit source files
1477
+ 📄 File mode — edit source files
1478
1478
  </UBadge>
1479
1479
  </template>
1480
1480
 
@@ -1557,7 +1557,7 @@ onMounted(() => {
1557
1557
  New Entry
1558
1558
  </UButton>
1559
1559
  <UBadge v-else color="warning" variant="subtle" class="gap-1.5 py-1 px-2.5">
1560
- 🔒 File-locked — read-only
1560
+ 📄 File mode — read-only
1561
1561
  </UBadge>
1562
1562
  </div>
1563
1563
  </template>
@@ -1706,7 +1706,7 @@ onMounted(() => {
1706
1706
  :description="col.description || 'No description provided'"
1707
1707
  :title="col.name"
1708
1708
  :badge="{
1709
- label: `${col.source || 'db'} | ${col.mode === 'file-lock' ? '🔒 File-locked' : col.mode === 'git-sync' ? '🌿 Git-sync' : '💾 Database'}`,
1709
+ label: `${col.source || 'db'} | ${col.mode === 'file' ? '📄 File' : col.mode === 'hybrid' ? '⚡ Hybrid' : '💾 Database'}`,
1710
1710
  }"
1711
1711
  :to="{ query: { ...route.query, collection: col.id } }"
1712
1712
  />
@@ -1,7 +1,8 @@
1
1
  import type { NitroApp } from "nitro/types";
2
2
  /**
3
- * Nitro server plugin for Qarpeo CMS. In development, automatically creates CMS tables and
4
- * synchronizes local `content/` files and `nuxt.config.ts` collections into D1 on startup. In
5
- * production, creates CMS tables (idempotent) so requests don't fail if migrations weren't run.
3
+ * Nitro server plugin for Qarpeo CMS.
4
+ *
5
+ * - In development: creates CMS tables and synchronizes local `content/` files and `nuxt.config.ts` collections into D1 on startup.
6
+ * - In production: creates CMS tables and seeds collections and pre-compiled manifest entries into D1 on startup.
6
7
  */
7
8
  export default function (_nitroApp?: NitroApp): void;
@@ -1,4 +1,9 @@
1
- import { ensureCMSSynced, ensureCMSTables } from "../utils/cms.mjs";
1
+ import {
2
+ ensureCMSSynced,
3
+ ensureCMSTables,
4
+ seedCollectionsFromConfig,
5
+ seedEntriesIntoDb
6
+ } from "../utils/cms.mjs";
2
7
  let tablesEnsured = false;
3
8
  export default function(_nitroApp) {
4
9
  if (process.env.NODE_ENV !== "production" || import.meta.dev) {
@@ -8,7 +13,18 @@ export default function(_nitroApp) {
8
13
  } else {
9
14
  if (!tablesEnsured) {
10
15
  tablesEnsured = true;
11
- ensureCMSTables().catch((err) => {
16
+ ensureCMSTables().then(async (event) => {
17
+ try {
18
+ const { manifestEntries, manifestCollections } = await import("#qarpeo/cms/manifest");
19
+ if (manifestCollections && Object.keys(manifestCollections).length > 0) {
20
+ await seedCollectionsFromConfig(event, manifestCollections);
21
+ }
22
+ if (manifestEntries && manifestEntries.length > 0) {
23
+ await seedEntriesIntoDb(event, manifestEntries, manifestCollections);
24
+ }
25
+ } catch {
26
+ }
27
+ }).catch((err) => {
12
28
  console.warn("[qarpeo:cms] Startup table creation warning:", err);
13
29
  });
14
30
  }
@@ -5,10 +5,10 @@ export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
6
  await requireAuth(event, { role: config.roles });
7
7
  const collection = getRouterParam(event, "collection");
8
- if (config.collections[collection]?.mode === "file-lock") {
8
+ if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
10
10
  statusCode: 403,
11
- message: `Collection "${collection}" is file-locked. Manage content via Git files.`
11
+ message: `Collection "${collection}" is in file mode. Manage content via Git files.`
12
12
  });
13
13
  }
14
14
  const id = getRouterParam(event, "id");
@@ -5,10 +5,10 @@ export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
6
  await requireAuth(event, { role: config.roles });
7
7
  const collection = getRouterParam(event, "collection");
8
- if (config.collections[collection]?.mode === "file-lock") {
8
+ if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
10
10
  statusCode: 403,
11
- message: `Collection "${collection}" is file-locked. Manage content via Git files.`
11
+ message: `Collection "${collection}" is in file mode. Manage content via Git files.`
12
12
  });
13
13
  }
14
14
  const id = getRouterParam(event, "id");
@@ -5,10 +5,10 @@ export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
6
  await requireAuth(event, { role: config.roles });
7
7
  const collection = getRouterParam(event, "collection");
8
- if (config.collections[collection]?.mode === "file-lock") {
8
+ if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
10
10
  statusCode: 403,
11
- message: `Collection "${collection}" is file-locked. Manage content via Git files.`
11
+ message: `Collection "${collection}" is in file mode. Manage content via Git files.`
12
12
  });
13
13
  }
14
14
  const id = getRouterParam(event, "id");
@@ -5,10 +5,10 @@ export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
6
  await requireAuth(event, { role: config.roles });
7
7
  const collection = getRouterParam(event, "collection");
8
- if (config.collections[collection]?.mode === "file-lock") {
8
+ if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
10
10
  statusCode: 403,
11
- message: `Collection "${collection}" is file-locked. Manage content via Git files.`
11
+ message: `Collection "${collection}" is in file mode. Manage content via Git files.`
12
12
  });
13
13
  }
14
14
  const id = getRouterParam(event, "id");
@@ -5,10 +5,10 @@ export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
6
  const { user } = await requireAuth(event, { role: config.roles });
7
7
  const collection = getRouterParam(event, "collection");
8
- if (config.collections[collection]?.mode === "file-lock") {
8
+ if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
10
10
  statusCode: 403,
11
- message: `Collection "${collection}" is file-locked. Manage content via Git files.`
11
+ message: `Collection "${collection}" is in file mode. Manage content via Git files.`
12
12
  });
13
13
  }
14
14
  const body = await readBody(event);
@@ -221,6 +221,15 @@ export declare function ensureCMSSynced(event?: any): Promise<void>;
221
221
  * - Source: 'db' rows (created from CMS Admin) are never touched.
222
222
  */
223
223
  export declare function seedCollectionsFromConfig(event: any, collectionsConfig: Record<string, CMSCollectionConfig>): Promise<void>;
224
+ /**
225
+ * Seeds or updates pre-scanned content entries into D1 database.
226
+ * Used by both build-time manifest auto-restore and dev-mode local file sync.
227
+ */
228
+ export declare function seedEntriesIntoDb(event: any, entries: any[], collectionsConfig?: Record<string, CMSCollectionConfig>): Promise<{
229
+ synced: number;
230
+ skipped: number;
231
+ inserted: number;
232
+ }>;
224
233
  /**
225
234
  * Scans local markdown files in contentDir and seeds them into D1. Auto-discovers collection
226
235
  * folders (e.g. content/posts/ -> 'posts' collection). For "page" type collections, recursively
@@ -319,7 +319,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
319
319
  const config = getCMSConfig(event);
320
320
  const colConfig = config.collections[collectionId] || {};
321
321
  const mode = colConfig.mode || config.mode || "db";
322
- if (mode !== "git-sync") {
322
+ if (mode !== "hybrid") {
323
323
  return null;
324
324
  }
325
325
  const result = {};
@@ -1850,6 +1850,16 @@ export async function ensureCMSSynced(event) {
1850
1850
  prodTablesChecked = true;
1851
1851
  try {
1852
1852
  await ensureCMSTables(event);
1853
+ try {
1854
+ const { manifestEntries, manifestCollections } = await import("#qarpeo/cms/manifest");
1855
+ if (manifestCollections && Object.keys(manifestCollections).length > 0) {
1856
+ await seedCollectionsFromConfig(event, manifestCollections);
1857
+ }
1858
+ if (manifestEntries && manifestEntries.length > 0) {
1859
+ await seedEntriesIntoDb(event, manifestEntries, manifestCollections);
1860
+ }
1861
+ } catch {
1862
+ }
1853
1863
  } catch (err) {
1854
1864
  console.warn("[qarpeo:cms] Production ensureCMSTables check failed:", err);
1855
1865
  }
@@ -1865,12 +1875,12 @@ export async function seedCollectionsFromConfig(event, collectionsConfig) {
1865
1875
  const existing = await db.prepare("SELECT id, source, schema_json FROM _qarpeo_cms_collections WHERE id = ?").bind(id).first();
1866
1876
  if (!existing) {
1867
1877
  await db.prepare(
1868
- "INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, created_at, updated_at) VALUES (?, ?, ?, ?, 'config', ?, ?)"
1869
- ).bind(id, colName, cfg.description ?? null, schemaJson, now, now).run();
1878
+ `INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, "order", created_at, updated_at) VALUES (?, ?, ?, ?, 'config', ?, ?, ?)`
1879
+ ).bind(id, colName, cfg.description ?? null, schemaJson, cfg.order ?? 0, now, now).run();
1870
1880
  } else if (existing.source === "config" && existing.schema_json !== schemaJson) {
1871
1881
  await db.prepare(
1872
- "UPDATE _qarpeo_cms_collections SET name = ?, description = ?, schema_json = ?, updated_at = ? WHERE id = ?"
1873
- ).bind(colName, cfg.description ?? null, schemaJson, now, id).run();
1882
+ 'UPDATE _qarpeo_cms_collections SET name = ?, description = ?, schema_json = ?, "order" = ?, updated_at = ? WHERE id = ?'
1883
+ ).bind(colName, cfg.description ?? null, schemaJson, cfg.order ?? 0, now, id).run();
1874
1884
  try {
1875
1885
  const kv = getKVBinding(event);
1876
1886
  const tenantPrefix = getCMSTenantPrefix(event);
@@ -1880,6 +1890,141 @@ export async function seedCollectionsFromConfig(event, collectionsConfig) {
1880
1890
  }
1881
1891
  }
1882
1892
  }
1893
+ export async function seedEntriesIntoDb(event, entries, collectionsConfig = {}) {
1894
+ const db = getCMSDb(event);
1895
+ let synced = 0;
1896
+ let skipped = 0;
1897
+ let inserted = 0;
1898
+ const now = Date.now();
1899
+ for (const entry of entries) {
1900
+ const colId = entry.collection_id;
1901
+ const colConfig = collectionsConfig[colId] || {};
1902
+ const mode = colConfig.mode || "db";
1903
+ try {
1904
+ const existingCol = await db.prepare("SELECT id FROM _qarpeo_cms_collections WHERE id = ?").bind(colId).first();
1905
+ if (!existingCol) {
1906
+ const colName = colConfig.name || colId.charAt(0).toUpperCase() + colId.slice(1).replace(/-/g, " ");
1907
+ await db.prepare(
1908
+ `INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, "order", created_at, updated_at) VALUES (?, ?, ?, '{}', 'config', ?, ?, ?)`
1909
+ ).bind(
1910
+ colId,
1911
+ colName,
1912
+ `Collection ${colName}`,
1913
+ colConfig.order ?? 0,
1914
+ now,
1915
+ now
1916
+ ).run();
1917
+ }
1918
+ } catch {
1919
+ }
1920
+ const existing = await db.prepare(
1921
+ "SELECT id, source, content_hash, metadata_json, file_path, status FROM _qarpeo_cms_entries WHERE collection_id = ? AND path = ?"
1922
+ ).bind(colId, entry.path).first();
1923
+ if (!existing) {
1924
+ const id = entry.id || nanoid();
1925
+ await db.prepare(
1926
+ `INSERT INTO _qarpeo_cms_entries
1927
+ (id, collection_id, slug, path, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, file_path, content_hash, published_at, created_at, updated_at)
1928
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'file', ?, ?, ?, ?, ?)`
1929
+ ).bind(
1930
+ id,
1931
+ colId,
1932
+ entry.slug,
1933
+ entry.path,
1934
+ entry.title,
1935
+ entry.description ?? null,
1936
+ entry.cover_image ?? null,
1937
+ entry.tags ?? null,
1938
+ entry.order ?? 0,
1939
+ entry.content_md ?? "",
1940
+ entry.content_html ?? "",
1941
+ entry.metadata_json ?? "{}",
1942
+ entry.status ?? "published",
1943
+ entry.file_path ?? "",
1944
+ entry.content_hash ?? "",
1945
+ entry.status === "draft" ? null : now,
1946
+ now,
1947
+ now
1948
+ ).run();
1949
+ inserted++;
1950
+ } else {
1951
+ if (mode === "file") {
1952
+ if (existing.content_hash !== entry.content_hash || existing.metadata_json !== entry.metadata_json || existing.status !== entry.status) {
1953
+ await db.prepare(
1954
+ `UPDATE _qarpeo_cms_entries SET
1955
+ status = ?, slug = ?, path = ?, title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
1956
+ content_md = ?, content_html = ?, metadata_json = ?,
1957
+ file_path = ?, content_hash = ?, source = 'file', updated_at = ?
1958
+ WHERE id = ?`
1959
+ ).bind(
1960
+ entry.status ?? "published",
1961
+ entry.slug,
1962
+ entry.path,
1963
+ entry.title,
1964
+ entry.description ?? null,
1965
+ entry.cover_image ?? null,
1966
+ entry.tags ?? null,
1967
+ entry.order ?? 0,
1968
+ entry.content_md ?? "",
1969
+ entry.content_html ?? "",
1970
+ entry.metadata_json ?? "{}",
1971
+ entry.file_path ?? "",
1972
+ entry.content_hash ?? "",
1973
+ now,
1974
+ existing.id
1975
+ ).run();
1976
+ synced++;
1977
+ } else {
1978
+ skipped++;
1979
+ }
1980
+ } else if (mode === "hybrid") {
1981
+ if (existing.source === "file") {
1982
+ if (existing.content_hash !== entry.content_hash) {
1983
+ await db.prepare(
1984
+ `UPDATE _qarpeo_cms_entries SET
1985
+ status = ?, slug = ?, path = ?, title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
1986
+ content_md = ?, content_html = ?, metadata_json = ?,
1987
+ file_path = ?, content_hash = ?, updated_at = ?
1988
+ WHERE id = ?`
1989
+ ).bind(
1990
+ entry.status ?? "published",
1991
+ entry.slug,
1992
+ entry.path,
1993
+ entry.title,
1994
+ entry.description ?? null,
1995
+ entry.cover_image ?? null,
1996
+ entry.tags ?? null,
1997
+ entry.order ?? 0,
1998
+ entry.content_md ?? "",
1999
+ entry.content_html ?? "",
2000
+ entry.metadata_json ?? "{}",
2001
+ entry.file_path ?? "",
2002
+ entry.content_hash ?? "",
2003
+ now,
2004
+ existing.id
2005
+ ).run();
2006
+ synced++;
2007
+ } else {
2008
+ skipped++;
2009
+ }
2010
+ } else {
2011
+ if (existing.content_hash !== entry.content_hash) {
2012
+ const revId = nanoid();
2013
+ await db.prepare(
2014
+ "INSERT INTO _qarpeo_cms_revisions (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, 'git', ?)"
2015
+ ).bind(revId, existing.id, entry.title, entry.content_md, entry.metadata_json, now).run();
2016
+ synced++;
2017
+ } else {
2018
+ skipped++;
2019
+ }
2020
+ }
2021
+ } else {
2022
+ skipped++;
2023
+ }
2024
+ }
2025
+ }
2026
+ return { synced, skipped, inserted };
2027
+ }
1883
2028
  import { matchesSourceFilters, matchesGlobFilter } from "./cms-filter.mjs";
1884
2029
  export { matchesSourceFilters, matchesGlobFilter };
1885
2030
  export async function syncLocalContentFiles(event, contentDir, collectionsConfig = {}, sources = []) {
@@ -2628,6 +2773,18 @@ export async function getCMSEntryByPath(event, collectionId, path, locale, optio
2628
2773
  `SELECT * FROM _qarpeo_cms_entries WHERE (path = ? OR path = ?) AND ${statusFilter}${tenantClause} ORDER BY ${statusOrder} created_at DESC LIMIT 1`
2629
2774
  ).bind(...binds3).first();
2630
2775
  }
2776
+ if (!row) {
2777
+ try {
2778
+ const { manifestEntries } = await import("#qarpeo/cms/manifest");
2779
+ const candidate = (manifestEntries || []).find(
2780
+ (e) => (e.collection_id === collectionId || collectionId === "content") && (e.path === cleanPath || e.path === `${cleanPath}/`)
2781
+ );
2782
+ if (candidate) {
2783
+ row = candidate;
2784
+ }
2785
+ } catch {
2786
+ }
2787
+ }
2631
2788
  if (!row) return null;
2632
2789
  const entry = rowToEntry(row);
2633
2790
  if ((!entry.body || !Array.isArray(entry.body.nodes)) && entry.contentMd) {
package/dist/types.d.ts CHANGED
@@ -1507,7 +1507,7 @@ export interface CMSCollectionConfig {
1507
1507
  * - `'file-lock'` — Read-only in CMS Admin. Content is managed via Git files/PRs only.
1508
1508
  * - `'git-sync'` — Dashboard edits write back to Git (via disk in dev, GitHub API in production).
1509
1509
  */
1510
- mode?: "db" | "file-lock" | "git-sync";
1510
+ mode?: "db" | "file" | "hybrid";
1511
1511
  /** Git sync configuration for this collection when mode is 'git-sync'. */
1512
1512
  github?: CMSGitHubConfig;
1513
1513
  /** Outgoing webhooks triggered by changes in this collection. */
@@ -0,0 +1,35 @@
1
+ import type { CMSCollectionConfig } from "../types";
2
+ export interface ScannedCMSEntry {
3
+ id?: string;
4
+ collection_id: string;
5
+ slug: string;
6
+ path: string;
7
+ title: string;
8
+ description: string | null;
9
+ cover_image: string | null;
10
+ tags: string | null;
11
+ order: number;
12
+ content_md: string;
13
+ content_html: string;
14
+ metadata_json: string;
15
+ status: "published" | "draft";
16
+ source: "file";
17
+ file_path: string;
18
+ content_hash: string;
19
+ published_at: number | null;
20
+ created_at: number;
21
+ updated_at: number;
22
+ }
23
+ export interface ScanContentOptions {
24
+ contentDir: string;
25
+ collectionsConfig?: Record<string, CMSCollectionConfig>;
26
+ sources?: any[];
27
+ exclude?: string | string[];
28
+ }
29
+ export declare function extractTOC(md: string): any[];
30
+ export declare function parseFrontmatter(raw: string): {
31
+ data: Record<string, unknown>;
32
+ content: string;
33
+ };
34
+ export declare function computeContentHash(text: string): string;
35
+ export declare function scanContentEntries(options: ScanContentOptions): Promise<ScannedCMSEntry[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qarpeo",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Zero-config Cloudflare Edge Platform for Nuxt",
5
5
  "keywords": [
6
6
  "analytics-engine",