Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ SESSION_SECRET=your_session_secret_here
ALLOWED_GITHUB_USERNAME=your_username_here
ADMIN_DEV_BYPASS=true

LABNOTES_DIR=/home/humanpatternlab/lab-api/content/labnotes
LABNOTES_DIR=content/labnotes


2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { registerLabNotesRoutes } from "./routes/labNotesRoutes.js";
import { registerAdminRoutes } from "./routes/adminRoutes.js";
import OpenApiValidator from "express-openapi-validator";
import { registerOpenApiRoutes } from "./routes/openapiRoutes.js";
import { registerAdminTokensRoutes } from "./routes/adminTokensRoutes.js";
import fs from "node:fs";
import path from "node:path";
import { env } from "./env.js";
Expand Down Expand Up @@ -228,6 +229,7 @@ export function createApp() {
registerHealthRoutes(api, dbPath);
registerAdminRoutes(api, db);
registerLabNotesRoutes(api, db);
registerAdminTokensRoutes(app, db);

// MOUNT THE ROUTER (this is what makes routes actually exist)
app.use("/", api); // ✅ canonical
Expand Down
1 change: 0 additions & 1 deletion src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import Database from "better-sqlite3";
import path from "path";
import { fileURLToPath } from "url";
import crypto from "crypto";
import { marked } from "marked";
import { env } from "./env.js";
import { nowIso, sha256Hex } from './lib/helpers.js';
import { migrateLabNotesSchema, LAB_NOTES_SCHEMA_VERSION } from "./db/migrateLabNotes.js";
Expand Down
19 changes: 19 additions & 0 deletions src/lib/markdownBlocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export function expandMascotBlocks(md: string): string {
// :::carmel ... :::
return md.replace(
/(^|\n):::carmel\s*\n([\s\S]*?)\n:::(?=\n|$)/g,
(_m, lead, body) => {
const text = body.trim();
// Escape HTML so users can't inject tags inside the block
const safe = text
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");

return `${lead}<div class="carmel-callout">
<div class="carmel-callout-title">😼 <strong>Carmel calls this:</strong></div>
<div class="carmel-callout-body">“${safe}”</div>
</div>`;
}
);
}
5 changes: 5 additions & 0 deletions src/mappers/labNotesMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ const ALLOWED_NOTE_TYPES: ReadonlySet<LabNoteType> = new Set([
"weather",
]);

marked.setOptions({
gfm: true,
breaks: false, // ✅ strict
});

/**
* deriveStatus
* If status is missing/invalid, infer from publish timestamp.
Expand Down
116 changes: 74 additions & 42 deletions src/routes/adminRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { randomUUID } from "node:crypto";
import { marked } from "marked";
import passport, { requireAdmin, isGithubOAuthEnabled } from "../auth.js";
import { syncLabNotesFromFs } from "../services/syncLabNotesFromFs.js";
import { normalizeLocale, sha256Hex } from "../lib/helpers.js";

marked.setOptions({
gfm: true,
breaks: false, // ✅ strict
});


export function registerAdminRoutes(app: any, db: Database.Database) {
// Must match your UI origin exactly (no trailing slash)
const UI_BASE_URL = process.env.UI_BASE_URL ?? "http://localhost:8001";
Expand Down Expand Up @@ -121,13 +128,32 @@ export function registerAdminRoutes(app: any, db: Database.Database) {

// ✅ Resolve canonical noteId by (slug, locale) to make upserts stable
const existing = db
.prepare("SELECT id FROM lab_notes WHERE slug = ? AND locale = ?")
.get(slug, noteLocale) as { id: string } | undefined;
.prepare("SELECT id, department_id, dept, type FROM lab_notes WHERE slug = ? AND locale = ?")
.get(slug, noteLocale) as
| { id: string; department_id: string | null; dept: string | null; type: string | null }
| undefined;

// If the row already exists, prefer its id over any incoming id.
// This prevents “identity drift” where (slug, locale) updates a different id.
const noteId = existing?.id ?? id ?? randomUUID();

const incomingDepartment =
typeof department_id === "string" && department_id.trim() ? department_id.trim() : null;

const incomingDept =
typeof dept === "string" && dept.trim() ? dept.trim() : null;

// Preserve existing if not provided, else default for brand-new notes
const resolvedDepartment =
incomingDepartment ?? existing?.department_id ?? "SCMS";

const resolvedDept =
incomingDept ?? existing?.dept ?? null;

// Type is identity-ish too; preserve if missing
const resolvedType =
(typeof type === "string" && type.trim() ? type.trim() : null) ?? existing?.type ?? "labnote";

const tx = db.transaction(() => {
// 1) Upsert metadata row (NO content_html writes, NO content_markdown column)
db.prepare(`
Expand All @@ -151,11 +177,11 @@ export function registerAdminRoutes(app: any, db: Database.Database) {
title=excluded.title,
type=excluded.type,
status=excluded.status,
dept=excluded.dept,
dept = COALESCE(excluded.dept, lab_notes.dept),
category=excluded.category,
excerpt=excluded.excerpt,
summary=excluded.summary,
department_id=excluded.department_id,
department_id = COALESCE(excluded.department_id, lab_notes.department_id),
shadow_density=excluded.shadow_density,
coherence_score=excluded.coherence_score,
safer_landing=excluded.safer_landing,
Expand All @@ -176,7 +202,7 @@ export function registerAdminRoutes(app: any, db: Database.Database) {
excerpt || "",
summary || "",

department_id || "SCMS",
incomingDepartment,
shadow_density ?? 0,
coherence_score ?? 1.0,
safer_landing ? 1 : 0,
Expand All @@ -200,7 +226,7 @@ export function registerAdminRoutes(app: any, db: Database.Database) {
const nextRev = (revRow?.maxRev ?? 0) + 1;

// 4) Create revision row (ledger truth)
const revisionId = crypto.randomUUID();
const revisionId = randomUUID();

const prevPointer = db
.prepare(`
Expand All @@ -219,7 +245,7 @@ export function registerAdminRoutes(app: any, db: Database.Database) {
status: noteStatus,
published: normalizedPublishedAt ?? undefined,
dept: dept ?? null,
department_id: department_id || "SCMS",
department_id: resolvedDepartment,
shadow_density: shadow_density ?? 0,
coherence_score: coherence_score ?? 1.0,
safer_landing: Boolean(safer_landing),
Expand Down Expand Up @@ -342,57 +368,63 @@ export function registerAdminRoutes(app: any, db: Database.Database) {
// ---------------------------------------------------------------------------
// Admin: Publish Lab Note (protected)
// ---------------------------------------------------------------------------
app.post("/admin/notes/:id/publish", requireAdmin, (req: Request, res: Response) => {
// Admin: Publish by slug + locale
app.post("/admin/notes/:slug/publish", requireAdmin, (req: Request, res: Response) => {
try {
const id = String(req.params.id ?? "").trim();
if (!id) return res.status(400).json({ error: "id is required" });
const slug = String(req.params.slug ?? "").trim();
const locale = normalizeLocale(String(req.query.locale ?? "en"));
if (!slug) return res.status(400).json({ error: "slug is required" });

const nowDate = new Date().toISOString().slice(0, 10);

const result = db
.prepare(
`
UPDATE lab_notes
SET
status = 'published',
published_at = COALESCE(published_at, ?),
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
WHERE id = ?
`
)
.run(nowDate, id);
const row = db
.prepare(`SELECT id FROM lab_notes WHERE slug = ? AND locale = ? LIMIT 1`)
.get(slug, locale) as { id: string } | undefined;

if (result.changes === 0) return res.status(404).json({ error: "Not found" });
return res.json({ ok: true, id, status: "published" });
if (!row) return res.status(404).json({ error: "Not found" });

db.prepare(`
UPDATE lab_notes
SET
status = 'published',
published_revision_id = current_revision_id,
published_at = COALESCE(published_at, ?),
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
WHERE id = ?
`).run(nowDate, row.id);

return res.json({ ok: true, slug, locale, id: row.id, status: "published" });
} catch (e: any) {
return res.status(500).json({ error: "Database error", details: String(e?.message ?? e) });
}
});


// ---------------------------------------------------------------------------
// Admin: Un-publish Lab Note (protected)
// ---------------------------------------------------------------------------
app.post("/admin/notes/:id/unpublish", requireAdmin, (req: Request, res: Response) => {
app.post("/admin/notes/:slug/unpublish", requireAdmin, (req: Request, res: Response) => {
try {
const id = String(req.params.id ?? "").trim();
if (!id) return res.status(400).json({ error: "id is required" });
const slug = String(req.params.slug ?? "").trim();
const locale = normalizeLocale(String(req.query.locale ?? "en"));
if (!slug) return res.status(400).json({ error: "slug is required" });

const result = db
.prepare(
`
UPDATE lab_notes
SET
status = 'draft',
published_at = NULL,
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
WHERE id = ?
`
)
.run(id);
const row = db
.prepare(`SELECT id FROM lab_notes WHERE slug = ? AND locale = ? LIMIT 1`)
.get(slug, locale) as { id: string } | undefined;

if (!row) return res.status(404).json({ error: "Not found" });

if (result.changes === 0) return res.status(404).json({ error: "Not found" });
return res.json({ ok: true, id, status: "draft" });
db.prepare(`
UPDATE lab_notes
SET
status = 'draft',
published_revision_id = NULL,
published_at = NULL,
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
WHERE id = ?
`).run(row.id);

return res.json({ ok: true, slug, locale, id: row.id, status: "draft" });
} catch (e: any) {
return res.status(500).json({ error: "Database error", details: String(e?.message ?? e) });
}
Expand Down
Loading