Files
crosscode-platform/packages/contracts/scripts/json-schemas.cjs
T
joshuaandClaude Opus 5.5 514a6d8bc0 contracts 1.20.0: devotionals, Bible passages, messaging.get, WhatsApp opt-out, App export
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12). Additive.

- crosscode.devotional/1, the Hub's devotionals reply, and the devotionals CSV
  import (parseCsv, checkDevotionalCsv, template), shared by the Hub and the App
- Bible books (USFM, English and Afrikaans), seven translations with YouVersion
  ids and copyright lines, parseBibleReference, youVersionUrl
- messaging.get and the messaging.changed hint; whatsapp.optout and
  whatsapp_opted_out on the profile
- APP_MODULES, hub.DEVOTIONALS_PATH, agent.APP_DEMO_PROFILES, app in DEMO_PRODUCTS
- the app section of the church export, people[].roles
- Accounts refuses the two new requests until 1.9.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:54:25 +02:00

137 lines
6.2 KiB
JavaScript

// Generates the JSON Schema files in `schemas/` from the zod schemas (ROADMAP-v3 §2), for
// consumers that don't use TypeScript or zod. Run after the build (`npm run build` does it):
// node scripts/json-schemas.cjs write schemas/
// node scripts/json-schemas.cjs --check fail if schemas/ is out of date
// The test (tests/json-schemas.test.ts) uses `buildSchemas` with the source, so the files in git
// always match the zod schemas.
const { z } = require("zod");
const fs = require("node:fs");
const path = require("node:path");
const BASE_ID = "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/";
/** File name (without .json) → schema, from the package exports (`c`) and `c.hub`. */
function contracts(c) {
return {
"event": c.eventSchema,
"event-feed": c.eventFeedSchema,
"event-changed": c.eventChangedSchema,
"church": c.churchSchema,
"identity-claims": c.identityClaimsSchema,
"accounts-call": c.accountsCallSchema,
"user-updated": c.userUpdatedSchema,
"user-updated-reply": c.userUpdatedReplySchema,
"user-deleted": c.userDeletedSchema,
"user-deleted-reply": c.userDeletedReplySchema,
"user-export": c.userExportSchema,
"user-export-reply": c.userExportReplySchema,
"hub-register-request": c.hub.registerRequestSchema,
"hub-register-response": c.hub.registerResponseSchema,
"hub-heartbeat-request": c.hub.heartbeatRequestSchema,
"hub-heartbeat-response": c.hub.heartbeatResponseSchema,
"hub-licence-payload": c.hub.licencePayloadSchema,
"hub-public-key-response": c.hub.publicKeyResponseSchema,
"hub-update-request": c.hub.updateRequestSchema,
"hub-update-request-response": c.hub.updateRequestResponseSchema,
"hub-update-request-cancel": c.hub.updateRequestCancelSchema,
"hub-update-request-cancel-response": c.hub.updateRequestCancelResponseSchema,
"hub-storage-request": c.hub.storageRequestSchema,
"hub-storage-request-response": c.hub.storageRequestResponseSchema,
"hub-ai-status-request": c.hub.aiStatusRequestSchema,
"hub-ai-status": c.hub.aiStatusSchema,
"hub-ai-complete-request": c.hub.aiCompleteRequestSchema,
"hub-ai-complete-response": c.hub.aiCompleteResponseSchema,
"hub-error": c.hub.hubErrorSchema,
"health": c.hub.healthSchema,
"agent-job": c.agent.agentJobSchema,
"agent-report": c.agent.agentReportSchema,
"script-report": c.agent.scriptReportSchema,
"agent-stats": c.agent.agentStatsSchema,
"agent-join-request": c.agent.joinRequestSchema,
"agent-join-response": c.agent.joinResponseSchema,
"agent-poll-request": c.agent.pollRequestSchema,
"agent-poll-response": c.agent.pollResponseSchema,
"agent-job-config": c.agent.jobConfigSchema,
"env-template": c.agent.envTemplateSchema,
"church-export": c.churchExportSchema,
"church-changed": c.churchChangedSchema,
"link-connect": c.linkConnectSchema,
"link-connected": c.linkConnectedSchema,
"link-disconnect": c.linkDisconnectSchema,
"link-disconnected": c.linkDisconnectedSchema,
"link-error": c.linkErrorSchema,
"identity-request": c.identityRequestSchema,
"import-person": c.importPersonSchema,
"import-begin-reply": c.importBeginReplySchema,
"import-batch-reply": c.importBatchReplySchema,
"import-finish-reply": c.importFinishReplySchema,
"people-ensure-reply": c.peopleEnsureReplySchema,
"messaging-status-reply": c.messagingStatusReplySchema,
"messaging-test-reply": c.messagingTestReplySchema,
"people-remove-demo-reply": c.peopleRemoveDemoReplySchema,
"people-check-reply": c.peopleCheckReplySchema,
"church-update-reply": c.churchUpdateReplySchema,
"messaging-get-reply": c.messagingGetReplySchema,
"messaging-changed": c.messagingChangedSchema,
"whatsapp-optout-reply": c.whatsappOptOutReplySchema,
"devotional": c.devotionalSchema,
"devotionals-reply": c.devotionalsReplySchema,
};
}
// zod writes .startsWith() / .endsWith() / .includes() as a `format` that isn't a JSON Schema
// format (strict validators such as Ajv refuse it) next to a `pattern` that does the real check.
const ZOD_ONLY_FORMATS = new Set(["starts_with", "ends_with", "includes"]);
function dropZodFormats(ctx) {
const json = ctx.jsonSchema;
if (ZOD_ONLY_FORMATS.has(json.format) && json.pattern) delete json.format;
}
/**
* name → JSON Schema (draft 2020-12). `io: "input"` describes what may be sent: unknown fields
* are allowed (consumers drop them, never refuse them) and defaults are optional.
* Checks zod can't express in JSON Schema (refinements, e.g. startsAt matching the sessions)
* only run in zod.
*/
function buildSchemas(c) {
const out = {};
for (const [name, schema] of Object.entries(contracts(c))) {
if (!schema) throw new Error(`json-schemas: no schema exported for "${name}"`);
out[name] = { $id: `${BASE_ID}${name}.json`, ...z.toJSONSchema(schema, { io: "input", override: dropZodFormats }) };
}
return out;
}
const serialise = (json) => `${JSON.stringify(json, null, 2)}\n`;
function main() {
const dir = path.join(__dirname, "..", "schemas");
const schemas = buildSchemas(require("../dist/index.js"));
const check = process.argv.includes("--check");
const stale = [];
if (!check) fs.mkdirSync(dir, { recursive: true });
const wanted = new Set(Object.keys(schemas).map((n) => `${n}.json`));
for (const [name, json] of Object.entries(schemas)) {
const file = path.join(dir, `${name}.json`);
const text = serialise(json);
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
if (current === text) continue;
if (check) stale.push(`${name}.json`);
else fs.writeFileSync(file, text);
}
for (const file of fs.existsSync(dir) ? fs.readdirSync(dir) : []) {
if (!file.endsWith(".json") || wanted.has(file)) continue;
if (check) stale.push(`${file} (no longer generated)`);
else fs.unlinkSync(path.join(dir, file));
}
if (check && stale.length) {
console.error(`schemas/ is out of date: ${stale.join(", ")}. Run npm run build.`);
process.exit(1);
}
console.log(check ? "schemas/ is up to date" : `Wrote ${Object.keys(schemas).length} JSON Schema files to schemas/`);
}
if (require.main === module) main();
module.exports = { buildSchemas, serialise };