العودة إلى الدرس

ملف العمل الأصلي

sync-records.mjs

تحتفظ الشيفرة وصفحات الأمثلة القابلة للتشغيل بمعرّفاتها ونصوصها التجريبية الأصلية. يشرحها الدرس وإرشادات الملفات بلغتك.

// Edit records.json, then let this script update the runnable copies.
import { readFile, writeFile } from "node:fs/promises";
const records = JSON.parse(
  await readFile(new URL("./records.json", import.meta.url), "utf8"),
);
if (
  !Array.isArray(records) ||
  records.length < 1 ||
  records.some(
    (r) =>
      !r ||
      typeof r.id !== "string" ||
      !/^[a-z]+$/.test(r.id) ||
      typeof r.title !== "string" ||
      !r.title.trim() ||
      typeof r.text !== "string" ||
      !r.text.trim() ||
      !Array.isArray(r.keywords) ||
      !r.keywords.length ||
      r.keywords.some((k) => typeof k !== "string" || !k.trim()),
  ) ||
  new Set(records.map((r) => r.id)).size !== records.length
) {
  throw Error(
    "Each record needs a unique lower-case id, title, text and keywords. No files changed.",
  );
}
const functionFile = new URL("./netlify/functions/mini-chat.mjs", import.meta.url);
const source = await readFile(functionFile, "utf8");
const marker = /\/\/ BEGIN GENERATED NOTES[\s\S]*?\/\/ END GENERATED NOTES/;
if (!marker.test(source))
  throw Error("Generated-notes markers are missing. No files changed.");
const next = source.replace(
  marker,
  "// BEGIN GENERATED NOTES\nconst records = " +
    JSON.stringify(records, null, 2) +
    ";\n// END GENERATED NOTES",
);
const escape = (text) =>
  text.replace(
    /[&<>"']/g,
    (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c],
  );
const sections = records
  .map(
    (r) =>
      '<section id="' +
      r.id +
      '"><h2>' +
      escape(r.title) +
      "</h2><p>" +
      escape(r.text) +
      "</p></section>",
  )
  .join("\n");
const html =
  '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Fictional Cedar café notes</title><link rel="stylesheet" href="style.css"></head><body><main><h1>Fictional Cedar café notes</h1><p>Practice information; not a real business.</p>' +
  sections +
  '<p><a href="index.html">Back to chat</a></p></main></body></html>\n';
await writeFile(functionFile, next);
await writeFile(new URL("./public/sources.html", import.meta.url), html);
await writeFile(
  new URL("./practice/records.json", import.meta.url),
  JSON.stringify(records, null, 2) + "\n",
);
await writeFile(
  new URL("./practice/records.js", import.meta.url),
  "window.PracticeCafeNotes = " + JSON.stringify(records, null, 2) + ";\n",
);
console.log(
  "Synced " +
    records.length +
    " notes to the server, source page and local practice. No AI request was made.",
);