aicms 0.0.0-stage → 0.5.0

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 (117) hide show
  1. package/ARCHITECTURE.md +467 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -2
  4. package/README.uk.md +201 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +722 -0
  7. package/dist/config-edit.d.ts +18 -0
  8. package/dist/config-edit.js +201 -0
  9. package/dist/config.d.ts +55 -0
  10. package/dist/config.js +32 -0
  11. package/dist/edge.d.ts +22 -0
  12. package/dist/edge.js +56 -0
  13. package/dist/gates/a2a.d.ts +45 -0
  14. package/dist/gates/a2a.js +126 -0
  15. package/dist/gates/discovery.d.ts +36 -0
  16. package/dist/gates/discovery.js +54 -0
  17. package/dist/gates/events.d.ts +14 -0
  18. package/dist/gates/events.js +86 -0
  19. package/dist/gates/graphql.d.ts +41 -0
  20. package/dist/gates/graphql.js +226 -0
  21. package/dist/gates/mcp.d.ts +8 -0
  22. package/dist/gates/mcp.js +60 -0
  23. package/dist/gates/openapi.d.ts +56 -0
  24. package/dist/gates/openapi.js +61 -0
  25. package/dist/gates/rest.d.ts +21 -0
  26. package/dist/gates/rest.js +263 -0
  27. package/dist/gates/studio.d.ts +21 -0
  28. package/dist/gates/studio.js +107 -0
  29. package/dist/index.d.ts +18 -0
  30. package/dist/index.js +19 -0
  31. package/dist/kernel/action.d.ts +49 -0
  32. package/dist/kernel/action.js +22 -0
  33. package/dist/kernel/briefs.d.ts +161 -0
  34. package/dist/kernel/briefs.js +197 -0
  35. package/dist/kernel/changesets.d.ts +367 -0
  36. package/dist/kernel/changesets.js +765 -0
  37. package/dist/kernel/cms.d.ts +127 -0
  38. package/dist/kernel/cms.js +419 -0
  39. package/dist/kernel/core-actions.d.ts +5 -0
  40. package/dist/kernel/core-actions.js +487 -0
  41. package/dist/kernel/errors.d.ts +14 -0
  42. package/dist/kernel/errors.js +25 -0
  43. package/dist/kernel/install.d.ts +32 -0
  44. package/dist/kernel/install.js +34 -0
  45. package/dist/kernel/model-actions.d.ts +5 -0
  46. package/dist/kernel/model-actions.js +126 -0
  47. package/dist/kernel/modules.d.ts +221 -0
  48. package/dist/kernel/modules.js +207 -0
  49. package/dist/kernel/policy.d.ts +42 -0
  50. package/dist/kernel/policy.js +47 -0
  51. package/dist/load.d.ts +10 -0
  52. package/dist/load.js +63 -0
  53. package/dist/modules/catalog.d.ts +15 -0
  54. package/dist/modules/catalog.js +21 -0
  55. package/dist/modules/commerce.d.ts +67 -0
  56. package/dist/modules/commerce.js +260 -0
  57. package/dist/modules/git-sync.d.ts +20 -0
  58. package/dist/modules/git-sync.js +187 -0
  59. package/dist/modules/i18n.d.ts +6 -0
  60. package/dist/modules/i18n.js +168 -0
  61. package/dist/modules/index.d.ts +9 -0
  62. package/dist/modules/index.js +10 -0
  63. package/dist/modules/lint.d.ts +22 -0
  64. package/dist/modules/lint.js +126 -0
  65. package/dist/modules/media.d.ts +52 -0
  66. package/dist/modules/media.js +319 -0
  67. package/dist/modules/payments.d.ts +19 -0
  68. package/dist/modules/payments.js +110 -0
  69. package/dist/modules/search.d.ts +27 -0
  70. package/dist/modules/search.js +81 -0
  71. package/dist/modules/seo.d.ts +34 -0
  72. package/dist/modules/seo.js +189 -0
  73. package/dist/modules/text.d.ts +10 -0
  74. package/dist/modules/text.js +42 -0
  75. package/dist/node.d.ts +7 -0
  76. package/dist/node.js +11 -0
  77. package/dist/registry.d.ts +57 -0
  78. package/dist/registry.js +110 -0
  79. package/dist/schema/fields.d.ts +100 -0
  80. package/dist/schema/fields.js +134 -0
  81. package/dist/schema/markdown.d.ts +7 -0
  82. package/dist/schema/markdown.js +168 -0
  83. package/dist/schema/model.d.ts +44 -0
  84. package/dist/schema/model.js +104 -0
  85. package/dist/schema/slug.d.ts +2 -0
  86. package/dist/schema/slug.js +40 -0
  87. package/dist/store/d1.d.ts +30 -0
  88. package/dist/store/d1.js +27 -0
  89. package/dist/store/postgres.d.ts +164 -0
  90. package/dist/store/postgres.js +552 -0
  91. package/dist/store/sql.d.ts +135 -0
  92. package/dist/store/sql.js +530 -0
  93. package/dist/store/sqlite.d.ts +14 -0
  94. package/dist/store/sqlite.js +60 -0
  95. package/dist/store/types.d.ts +226 -0
  96. package/dist/store/types.js +21 -0
  97. package/dist/studio/assets/geologica-cyrillic-ext-wght-normal-C8B9Chlh.woff2 +0 -0
  98. package/dist/studio/assets/geologica-cyrillic-wght-normal-DbeVG3Ps.woff2 +0 -0
  99. package/dist/studio/assets/geologica-greek-wght-normal-DPM5d9ub.woff2 +0 -0
  100. package/dist/studio/assets/geologica-latin-ext-wght-normal-DZyYlgcm.woff2 +0 -0
  101. package/dist/studio/assets/geologica-latin-wght-normal-BBL8hQxZ.woff2 +0 -0
  102. package/dist/studio/assets/geologica-vietnamese-wght-normal-DcI17N1q.woff2 +0 -0
  103. package/dist/studio/assets/index-3dJ0YHxb.js +22 -0
  104. package/dist/studio/assets/index-DuyGLFw4.css +1 -0
  105. package/dist/studio/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  106. package/dist/studio/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  107. package/dist/studio/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  108. package/dist/studio/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  109. package/dist/studio/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  110. package/dist/studio/assets/unbounded-cyrillic-wght-normal-C627f1f8.woff2 +0 -0
  111. package/dist/studio/assets/unbounded-latin-ext-wght-normal-D6H-S6MW.woff2 +0 -0
  112. package/dist/studio/assets/unbounded-latin-wght-normal-D5afBTBx.woff2 +0 -0
  113. package/dist/studio/assets/unbounded-vietnamese-wght-normal-rat7GD3o.woff2 +0 -0
  114. package/dist/studio/index.html +21 -0
  115. package/dist/typegen.d.ts +7 -0
  116. package/dist/typegen.js +55 -0
  117. package/package.json +88 -4
@@ -0,0 +1,319 @@
1
+ import { z } from "zod";
2
+ import { action } from "../kernel/action.js";
3
+ import { newId } from "../kernel/changesets.js";
4
+ import { AicmsError } from "../kernel/errors.js";
5
+ import { defineModule } from "../kernel/modules.js";
6
+ import { allows } from "../kernel/policy.js";
7
+ import { slugify } from "../schema/slug.js";
8
+ /** Files on disk, under the module's data folder (servers). */
9
+ export function localStorage(dir) {
10
+ const path = async (key) => (await import("node:path")).join(dir(), "files", key);
11
+ return {
12
+ async put(key, bytes) {
13
+ const fs = await import("node:fs/promises");
14
+ const file = await path(key);
15
+ await fs.mkdir((await import("node:path")).dirname(file), { recursive: true });
16
+ await fs.writeFile(file, bytes);
17
+ },
18
+ async get(key) {
19
+ const fs = await import("node:fs/promises");
20
+ try {
21
+ const file = await path(key);
22
+ const info = await fs.stat(file);
23
+ const { createReadStream } = await import("node:fs");
24
+ const { Readable } = await import("node:stream");
25
+ return { body: Readable.toWeb(createReadStream(file)), size: info.size };
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ },
31
+ async delete(key) {
32
+ const fs = await import("node:fs/promises");
33
+ await fs.rm((await path(key)).replace(/[\\/][^\\/]+$/, ""), { recursive: true, force: true });
34
+ },
35
+ };
36
+ }
37
+ /** Files in a Cloudflare R2 bucket, by binding name (edge). */
38
+ export function r2Storage(bucket) {
39
+ return {
40
+ put: async (key, bytes, type) => void (await bucket().put(key, bytes, { httpMetadata: { contentType: type } })),
41
+ get: async (key) => {
42
+ const obj = await bucket().get(key);
43
+ return obj ? { body: obj.body, size: obj.size } : null;
44
+ },
45
+ delete: (key) => bucket().delete(key),
46
+ };
47
+ }
48
+ const isIPv4 = (s) => /^\d{1,3}(\.\d{1,3}){3}$/.test(s);
49
+ const isIP = (s) => (isIPv4(s) ? 4 : s.includes(":") ? 6 : 0);
50
+ /** Loopback, private, link-local and other non-public ranges (IPv4 and IPv6). */
51
+ export function isPrivateAddress(ip) {
52
+ if (isIP(ip) === 4) {
53
+ const [a, b] = ip.split(".").map(Number);
54
+ return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || a >= 224;
55
+ }
56
+ const v6 = ip.toLowerCase();
57
+ if (v6.startsWith("::ffff:"))
58
+ return isPrivateAddress(v6.slice(7));
59
+ return v6 === "::" || v6 === "::1" || v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("fe8") || v6.startsWith("fe9") || v6.startsWith("fea") || v6.startsWith("feb");
60
+ }
61
+ const TYPES = [
62
+ ["image/png", (b) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))],
63
+ ["image/jpeg", (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
64
+ ["image/gif", (b) => b.subarray(0, 6).toString("latin1") === "GIF87a" || b.subarray(0, 6).toString("latin1") === "GIF89a"],
65
+ ["image/webp", (b) => b.subarray(0, 4).toString("latin1") === "RIFF" && b.subarray(8, 12).toString("latin1") === "WEBP"],
66
+ ["image/avif", (b) => b.subarray(4, 8).toString("latin1") === "ftyp" && /avi[fs]/.test(b.subarray(8, 12).toString("latin1"))],
67
+ ["application/pdf", (b) => b.subarray(0, 5).toString("latin1") === "%PDF-"],
68
+ ["image/svg+xml", (b) => /^\s*(<\?xml[^>]*>\s*)?(<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(b.subarray(0, 2048).toString("utf8"))],
69
+ ];
70
+ /** The type from the file's own bytes; the name or a client header is never trusted. */
71
+ export function sniff(buf) {
72
+ return TYPES.find(([, test]) => test(buf))?.[0] ?? null;
73
+ }
74
+ /** Width and height read from the image header (PNG, JPEG, GIF, WebP), without decoding it. */
75
+ export function imageSize(buf) {
76
+ try {
77
+ if (sniff(buf) === "image/png")
78
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
79
+ if (sniff(buf) === "image/gif")
80
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
81
+ if (sniff(buf) === "image/webp") {
82
+ const chunk = buf.subarray(12, 16).toString("latin1");
83
+ if (chunk === "VP8X")
84
+ return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };
85
+ if (chunk === "VP8L") {
86
+ const bits = buf.readUInt32LE(21);
87
+ return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff) };
88
+ }
89
+ if (chunk === "VP8 ")
90
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
91
+ }
92
+ if (sniff(buf) === "image/jpeg") {
93
+ let i = 2;
94
+ while (i < buf.length) {
95
+ if (buf[i] !== 0xff)
96
+ return null;
97
+ const marker = buf[i + 1];
98
+ const len = buf.readUInt16BE(i + 2);
99
+ // SOF0–SOF15 except DHT (C4), JPG (C8) and DAC (CC) carry the frame size.
100
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker))
101
+ return { width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5) };
102
+ i += 2 + len;
103
+ }
104
+ }
105
+ }
106
+ catch {
107
+ /* truncated header */
108
+ }
109
+ return null;
110
+ }
111
+ const EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp", "image/avif": "avif", "application/pdf": "pdf", "image/svg+xml": "svg" };
112
+ function safeName(name, mime) {
113
+ const raw = (name ?? "").split(/[\\/]/).pop() ?? "";
114
+ const dot = raw.lastIndexOf(".");
115
+ const base = slugify(dot > 0 ? raw.slice(0, dot) : raw, 60) || "file";
116
+ return `${base}.${EXT[mime]}`;
117
+ }
118
+ /** Media library: uploads (file, URL or base64), image sizes, alt text, served under /media. */
119
+ export function media(opts = {}) {
120
+ const maxBytes = opts.maxBytes ?? 10 * 1024 * 1024;
121
+ const base = (opts.baseUrl ?? "").replace(/\/+$/, "");
122
+ let storage;
123
+ const files = (ctx) => (storage ??= typeof opts.storage === "object" ? r2Storage(() => ctx.binding(opts.storage.r2)) : localStorage(() => ctx.dataDir));
124
+ const keyOf = (row) => `${row.id}/${row.filename}`;
125
+ const tooBig = () => new AicmsError("invalid", `Files may be up to ${Math.round(maxBytes / 1024 / 1024)} MB`);
126
+ async function store(ctx, buf, name, alt) {
127
+ if (!buf.length)
128
+ throw new AicmsError("invalid", "The file is empty");
129
+ if (buf.length > maxBytes)
130
+ throw tooBig();
131
+ const mime = sniff(buf);
132
+ if (!mime)
133
+ throw new AicmsError("invalid", "Unsupported file. Upload PNG, JPEG, GIF, WebP, AVIF, SVG or PDF.");
134
+ const id = newId("med");
135
+ const filename = safeName(name, mime);
136
+ const row = {
137
+ id,
138
+ url: `${base}/media/${id}/${filename}`,
139
+ filename,
140
+ mime,
141
+ size: buf.length,
142
+ ...(imageSize(buf) ?? {}),
143
+ ...(alt?.trim() ? { alt: alt.trim() } : {}),
144
+ createdAt: new Date().toISOString(),
145
+ createdBy: ctx.actor.id,
146
+ };
147
+ await files(ctx).put(keyOf(row), buf, mime);
148
+ await ctx.media.create(row);
149
+ return row;
150
+ }
151
+ async function download(url) {
152
+ let u;
153
+ try {
154
+ u = new URL(url);
155
+ }
156
+ catch {
157
+ throw new AicmsError("invalid", "Not a valid URL");
158
+ }
159
+ // Follow redirects by hand so every hop is checked against private networks (SSRF).
160
+ let res;
161
+ for (let hop = 0; hop < 4; hop++) {
162
+ if (!/^https?:$/.test(u.protocol))
163
+ throw new AicmsError("invalid", "Only http(s) URLs can be imported");
164
+ if (!opts.allowPrivateNetworks) {
165
+ const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
166
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".internal"))
167
+ throw new AicmsError("forbidden", `${u.hostname} points to a private network address`);
168
+ let addresses = isIP(host) ? [host] : [];
169
+ if (!addresses.length) {
170
+ // Servers resolve the name; the edge has no resolver but can't reach private networks anyway.
171
+ const dns = await import("node:dns/promises").catch(() => null);
172
+ if (dns?.lookup) {
173
+ addresses = (await dns.lookup(host, { all: true }).catch(() => [])).map((a) => a.address);
174
+ if (!addresses.length)
175
+ throw new AicmsError("invalid", `Can't resolve ${u.hostname}`);
176
+ }
177
+ }
178
+ if (addresses.some(isPrivateAddress))
179
+ throw new AicmsError("forbidden", `${u.hostname} points to a private network address`);
180
+ }
181
+ res = await fetch(u, { signal: AbortSignal.timeout(15_000), redirect: "manual" });
182
+ const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
183
+ if (!location)
184
+ break;
185
+ u = new URL(location, u);
186
+ res = undefined;
187
+ }
188
+ if (!res)
189
+ throw new AicmsError("invalid", "Too many redirects");
190
+ if (!res.ok || !res.body)
191
+ throw new AicmsError("invalid", `Couldn't download ${url}: HTTP ${res.status}`);
192
+ if (Number(res.headers.get("content-length") ?? 0) > maxBytes)
193
+ throw tooBig();
194
+ const chunks = [];
195
+ let size = 0;
196
+ for await (const chunk of res.body) {
197
+ size += chunk.length;
198
+ if (size > maxBytes)
199
+ throw tooBig();
200
+ chunks.push(Buffer.from(chunk));
201
+ }
202
+ return { buf: Buffer.concat(chunks), name: decodeURIComponent(u.pathname.split("/").pop() ?? "") };
203
+ }
204
+ return defineModule({
205
+ name: "media",
206
+ description: "Media library: upload files or import them from URLs, image sizes, alt text, served under /media.",
207
+ provides: ["media"],
208
+ actions: {
209
+ upload: action({
210
+ description: "Add a file to the media library from a URL or base64 data. Returns { id, url, width, height }; put the url in a media field or an image block.",
211
+ scope: "media:upload",
212
+ input: z.strictObject({
213
+ url: z.string().url().optional().describe("Import from this http(s) URL"),
214
+ data: z.string().optional().describe("Base64 file contents (instead of url)"),
215
+ filename: z.string().max(200).optional(),
216
+ alt: z.string().max(500).optional().describe("What the image shows, for people who can't see it"),
217
+ }),
218
+ async run({ input, ctx }) {
219
+ if (!!input.url === !!input.data)
220
+ throw new AicmsError("invalid", "Pass either url or data");
221
+ if (input.url) {
222
+ if (opts.allowRemote === false)
223
+ throw new AicmsError("forbidden", "Importing from URLs is turned off");
224
+ const { buf, name } = await download(input.url);
225
+ return store(ctx, buf, input.filename ?? name, input.alt);
226
+ }
227
+ return store(ctx, Buffer.from(input.data, "base64"), input.filename, input.alt);
228
+ },
229
+ }),
230
+ list: action({
231
+ description: "Files in the media library, newest first. missingAlt: true lists images that still need alt text.",
232
+ scope: "media:read",
233
+ readOnly: true,
234
+ input: z.strictObject({
235
+ query: z.string().optional(),
236
+ missingAlt: z.boolean().optional(),
237
+ limit: z.number().int().min(1).max(100).optional(),
238
+ offset: z.number().int().min(0).optional(),
239
+ }),
240
+ run: ({ input, ctx }) => ctx.media.list({ query: input.query, missingAlt: input.missingAlt, limit: input.limit ?? 30, offset: input.offset ?? 0 }),
241
+ }),
242
+ get: action({
243
+ description: "One file's details.",
244
+ scope: "media:read",
245
+ readOnly: true,
246
+ input: z.strictObject({ id: z.string().min(1) }),
247
+ async run({ input, ctx }) {
248
+ const row = await ctx.media.get(input.id);
249
+ if (!row)
250
+ throw new AicmsError("not_found", `No media ${input.id}`);
251
+ return row;
252
+ },
253
+ }),
254
+ update: action({
255
+ description: "Set a file's alt text.",
256
+ scope: "media:update",
257
+ input: z.strictObject({ id: z.string().min(1), alt: z.string().max(500) }),
258
+ async run({ input, ctx }) {
259
+ const row = await ctx.media.update(input.id, { alt: input.alt.trim() });
260
+ if (!row)
261
+ throw new AicmsError("not_found", `No media ${input.id}`);
262
+ return row;
263
+ },
264
+ }),
265
+ delete: action({
266
+ description: "Delete a file from the library. Entries that still use its URL will show a broken image.",
267
+ scope: "media:delete",
268
+ destructive: true,
269
+ input: z.strictObject({ id: z.string().min(1) }),
270
+ async run({ input, ctx }) {
271
+ const row = await ctx.media.get(input.id);
272
+ if (!row)
273
+ throw new AicmsError("not_found", `No media ${input.id}`);
274
+ await ctx.media.delete(input.id);
275
+ await files(ctx).delete(keyOf(row));
276
+ return { deleted: input.id };
277
+ },
278
+ }),
279
+ },
280
+ routes: {
281
+ // Raw-body upload for Studio and scripts: POST /media/upload with x-filename (and optional x-alt).
282
+ "POST /media/upload": async ({ request, ctx }) => {
283
+ if (!allows(ctx.actor.scopes, "media:upload")) {
284
+ return Response.json({ error: { code: ctx.actor.kind === "public" ? "unauthorized" : "forbidden", message: "Uploading needs the media:upload scope" } }, { status: ctx.actor.kind === "public" ? 401 : 403 });
285
+ }
286
+ if (Number(request.headers.get("content-length") ?? 0) > maxBytes)
287
+ return Response.json({ error: { code: "invalid", message: tooBig().message } }, { status: 413 });
288
+ try {
289
+ const buf = Buffer.from(await request.arrayBuffer());
290
+ const decode = (h) => (h ? decodeURIComponent(h) : undefined);
291
+ const row = await store(ctx, buf, decode(request.headers.get("x-filename")), decode(request.headers.get("x-alt")));
292
+ return Response.json(row, { status: 201 });
293
+ }
294
+ catch (e) {
295
+ const err = e instanceof AicmsError ? e : new AicmsError("invalid", String(e));
296
+ return Response.json({ error: err.toJSON() }, { status: err.status });
297
+ }
298
+ },
299
+ "GET /media/:id/:name": async ({ params, ctx }) => {
300
+ const row = await ctx.media.get(params.id);
301
+ if (!row || row.filename !== params.name)
302
+ return new Response("Not found", { status: 404 });
303
+ const file = await files(ctx).get(keyOf(row));
304
+ if (!file)
305
+ return new Response("Not found", { status: 404 });
306
+ const headers = {
307
+ "content-type": row.mime,
308
+ "content-length": String(row.size),
309
+ "cache-control": "public, max-age=31536000, immutable",
310
+ "x-content-type-options": "nosniff",
311
+ };
312
+ // An SVG can carry scripts: serve it inert.
313
+ if (row.mime === "image/svg+xml")
314
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
315
+ return new Response(file.body, { headers });
316
+ },
317
+ },
318
+ });
319
+ }
@@ -0,0 +1,19 @@
1
+ export interface ManualPaymentsOptions {
2
+ /** Shown to the customer after checkout: bank details, cash on delivery, pickup… */
3
+ instructions?: string;
4
+ }
5
+ /** Payments handled outside AICMS (bank transfer, cash on delivery). A person marks orders paid. */
6
+ export declare function manualPayments(opts?: ManualPaymentsOptions): import("../kernel/modules.ts").ModuleDef;
7
+ export interface StripeOptions {
8
+ /** sk_live_… or sk_test_… (e.g. process.env.STRIPE_SECRET_KEY). */
9
+ secretKey?: string;
10
+ /** whsec_… from the webhook endpoint pointing at /payments/stripe/webhook. */
11
+ webhookSecret?: string;
12
+ /** For tests: a fetch that talks to a fake Stripe. */
13
+ fetch?: typeof fetch;
14
+ apiBase?: string;
15
+ }
16
+ /** Verify a Stripe-Signature header: t=<unix>,v1=<hex hmac of "t.payload">, within `toleranceSec`. */
17
+ export declare function verifyStripeSignature(payload: string, header: string, secret: string, toleranceSec?: number, now?: number): boolean;
18
+ /** Stripe Checkout: a hosted payment page per order, confirmed by a signed webhook. */
19
+ export declare function stripe(opts?: StripeOptions): import("../kernel/modules.ts").ModuleDef;
@@ -0,0 +1,110 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { AicmsError } from "../kernel/errors.js";
3
+ import { defineModule } from "../kernel/modules.js";
4
+ /** Payments handled outside AICMS (bank transfer, cash on delivery). A person marks orders paid. */
5
+ export function manualPayments(opts = {}) {
6
+ const service = {
7
+ name: "manual",
8
+ instructions: opts.instructions ?? "We'll contact you about payment.",
9
+ createPayment: async ({ order }) => ({ ref: `manual-${order}`, status: "pending" }),
10
+ };
11
+ return defineModule({
12
+ name: "manual-payments",
13
+ description: "Payments outside AICMS: bank transfer, cash on delivery. Orders wait until a person marks them paid.",
14
+ provides: ["payments"],
15
+ services: { payments: service },
16
+ });
17
+ }
18
+ /** Verify a Stripe-Signature header: t=<unix>,v1=<hex hmac of "t.payload">, within `toleranceSec`. */
19
+ export function verifyStripeSignature(payload, header, secret, toleranceSec = 300, now = Date.now()) {
20
+ const parts = Object.fromEntries(header.split(",").map((kv) => kv.split("=", 2)));
21
+ const t = Number(parts.t);
22
+ if (!t || Math.abs(now / 1000 - t) > toleranceSec)
23
+ return false;
24
+ const expected = createHmac("sha256", secret).update(`${t}.${payload}`).digest();
25
+ return header
26
+ .split(",")
27
+ .filter((kv) => kv.startsWith("v1="))
28
+ .some((kv) => {
29
+ const got = Buffer.from(kv.slice(3), "hex");
30
+ return got.length === expected.length && timingSafeEqual(got, expected);
31
+ });
32
+ }
33
+ /** Stripe Checkout: a hosted payment page per order, confirmed by a signed webhook. */
34
+ export function stripe(opts = {}) {
35
+ const api = (opts.apiBase ?? "https://api.stripe.com").replace(/\/+$/, "");
36
+ const doFetch = opts.fetch ?? fetch;
37
+ const key = () => {
38
+ if (!opts.secretKey)
39
+ throw new AicmsError("invalid", "Stripe needs a secret key: stripe({ secretKey: process.env.STRIPE_SECRET_KEY })");
40
+ return opts.secretKey;
41
+ };
42
+ async function call(path, form, idempotencyKey) {
43
+ const res = await doFetch(`${api}${path}`, {
44
+ method: "POST",
45
+ headers: {
46
+ authorization: `Bearer ${key()}`,
47
+ "content-type": "application/x-www-form-urlencoded",
48
+ ...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}),
49
+ },
50
+ body: new URLSearchParams(form).toString(),
51
+ });
52
+ const body = await res.json().catch(() => ({}));
53
+ if (!res.ok)
54
+ throw new AicmsError("invalid", `Stripe: ${body?.error?.message ?? `HTTP ${res.status}`}`);
55
+ return body;
56
+ }
57
+ const service = {
58
+ name: "stripe",
59
+ async createPayment({ order, amount, currency, description, customerEmail, successUrl, cancelUrl }) {
60
+ if (!successUrl || !cancelUrl)
61
+ throw new AicmsError("invalid", "Stripe Checkout needs successUrl and cancelUrl (commerce options or the checkout request)");
62
+ const s = await call("/v1/checkout/sessions", {
63
+ mode: "payment",
64
+ "line_items[0][quantity]": "1",
65
+ "line_items[0][price_data][currency]": currency.toLowerCase(),
66
+ "line_items[0][price_data][unit_amount]": String(amount),
67
+ "line_items[0][price_data][product_data][name]": `Order ${order}`,
68
+ "line_items[0][price_data][product_data][description]": description.slice(0, 300) || `Order ${order}`,
69
+ success_url: successUrl,
70
+ cancel_url: cancelUrl,
71
+ client_reference_id: order,
72
+ "metadata[order]": order,
73
+ ...(customerEmail ? { customer_email: customerEmail } : {}),
74
+ }, `aicms-order-${order}`);
75
+ return { ref: s.id, url: s.url, status: s.payment_status === "paid" ? "paid" : "pending" };
76
+ },
77
+ async refund({ ref }) {
78
+ const r = await call("/v1/refunds", { payment_intent: ref }, `aicms-refund-${ref}`);
79
+ return { status: r.status === "succeeded" ? "refunded" : "pending" };
80
+ },
81
+ };
82
+ return defineModule({
83
+ name: "stripe",
84
+ description: "Stripe Checkout: hosted payment pages, confirmed by signed webhooks; refunds.",
85
+ provides: ["payments"],
86
+ services: { payments: service },
87
+ routes: {
88
+ "POST /payments/stripe/webhook": async ({ request, ctx }) => {
89
+ if (!opts.webhookSecret)
90
+ return Response.json({ error: { code: "invalid", message: "stripe({ webhookSecret }) is not set" } }, { status: 500 });
91
+ const payload = await request.text();
92
+ if (!verifyStripeSignature(payload, request.headers.get("stripe-signature") ?? "", opts.webhookSecret)) {
93
+ return Response.json({ error: { code: "unauthorized", message: "Bad Stripe signature" } }, { status: 400 });
94
+ }
95
+ const event = JSON.parse(payload);
96
+ const o = event.data?.object ?? {};
97
+ const report = (u) => ctx.emit("payment.updated", { provider: "stripe", ...u });
98
+ if (event.type === "checkout.session.completed" && o.payment_status === "paid")
99
+ await report({ ref: o.id, status: "paid", intent: o.payment_intent });
100
+ else if (event.type === "checkout.session.async_payment_succeeded")
101
+ await report({ ref: o.id, status: "paid", intent: o.payment_intent });
102
+ else if (event.type === "checkout.session.expired" || event.type === "checkout.session.async_payment_failed")
103
+ await report({ ref: o.id, status: "failed" });
104
+ else if (event.type === "charge.refunded" && o.payment_intent)
105
+ await report({ ref: o.payment_intent, status: "refunded" });
106
+ return Response.json({ received: true });
107
+ },
108
+ },
109
+ });
110
+ }
@@ -0,0 +1,27 @@
1
+ export interface SearchHit {
2
+ model: string;
3
+ id: string;
4
+ locale: string;
5
+ title: string;
6
+ field?: string;
7
+ snippet: string;
8
+ score: number;
9
+ }
10
+ /** The "search" capability: what cms.search calls when a search module is installed. */
11
+ export interface SearchService {
12
+ query(input: {
13
+ query: string;
14
+ models: string[];
15
+ locale?: string;
16
+ limit: number;
17
+ }): Promise<SearchHit[]>;
18
+ }
19
+ export interface SearchOptions {
20
+ /** Models to index. Default: all. */
21
+ models?: string[];
22
+ }
23
+ /**
24
+ * Full-text search with ranking (TF-IDF, title boost, prefix matching, any language).
25
+ * Keeps an index current on every merge; `cms.search` uses it automatically.
26
+ */
27
+ export declare function search(opts?: SearchOptions): import("../kernel/modules.ts").ModuleDef;
@@ -0,0 +1,81 @@
1
+ import { z } from "zod";
2
+ import { action } from "../kernel/action.js";
3
+ import { defineModule } from "../kernel/modules.js";
4
+ import { entryText, snippet, tokenize } from "./text.js";
5
+ /**
6
+ * Full-text search with ranking (TF-IDF, title boost, prefix matching, any language).
7
+ * Keeps an index current on every merge; `cms.search` uses it automatically.
8
+ */
9
+ export function search(opts = {}) {
10
+ let ctx;
11
+ const indexed = (model) => !opts.models || opts.models.includes(model);
12
+ async function indexEntry(c, id) {
13
+ const e = await c.entry(id);
14
+ if (!e || !indexed(e.model))
15
+ return c.text.remove(id);
16
+ const model = c.models().find((m) => m.name === e.model);
17
+ const { title, body } = entryText(model, e.data);
18
+ const terms = {};
19
+ for (const t of tokenize(title))
20
+ terms[t] = (terms[t] ?? 0) + 3;
21
+ for (const t of tokenize(body))
22
+ terms[t] = (terms[t] ?? 0) + 1;
23
+ await c.text.upsert({ id, model: e.model, locale: e.locale, title, body, terms });
24
+ }
25
+ async function reindex(c) {
26
+ await c.text.clear();
27
+ let count = 0;
28
+ for (const m of c.models()) {
29
+ if (!indexed(m.name))
30
+ continue;
31
+ for (let offset = 0;; offset += 200) {
32
+ const page = await c.list(m.name, { limit: 200, offset });
33
+ for (const item of page.items) {
34
+ await indexEntry(c, item.id);
35
+ count++;
36
+ }
37
+ if (offset + 200 >= page.total)
38
+ break;
39
+ }
40
+ }
41
+ return count;
42
+ }
43
+ const service = {
44
+ async query({ query, models, locale, limit }) {
45
+ if (!ctx)
46
+ return [];
47
+ const terms = tokenize(query);
48
+ const hits = await ctx.text.search({ terms, prefixLast: !/\s$/.test(query), models: models.filter(indexed), locale, limit });
49
+ return hits.map((h) => ({ model: h.model, id: h.id, locale: h.locale, title: h.title, snippet: snippet(h.body || h.title, terms), score: Math.round(h.score * 100) / 100 }));
50
+ },
51
+ };
52
+ return defineModule({
53
+ name: "search",
54
+ description: "Full-text search with ranking, prefix matching and any language. Replaces the simple scan behind cms.search.",
55
+ provides: ["search"],
56
+ uses: ["*"],
57
+ services: { search: service },
58
+ async setup(c) {
59
+ ctx = c;
60
+ if ((await c.text.count()) === 0)
61
+ await reindex(c);
62
+ },
63
+ on: {
64
+ "changeset.merged": async ({ payload, ctx: c }) => {
65
+ for (const e of payload.entries ?? [])
66
+ await indexEntry(c, e.id);
67
+ },
68
+ },
69
+ actions: {
70
+ reindex: action({
71
+ description: "Rebuild the search index from scratch.",
72
+ scope: "search:admin",
73
+ input: z.strictObject({}),
74
+ async run({ ctx: c }) {
75
+ // Index what is published, not the caller's drafts: use the module's own context.
76
+ return { indexed: await reindex(ctx ?? c) };
77
+ },
78
+ }),
79
+ },
80
+ });
81
+ }
@@ -0,0 +1,34 @@
1
+ import { type Model } from "../schema/model.ts";
2
+ export interface SeoOptions {
3
+ /** The public site's origin, e.g. "https://example.com". Used for sitemap.xml. */
4
+ siteUrl?: string;
5
+ /** Models to audit and list in the sitemap. Default: every model with a slug field. */
6
+ models?: string[];
7
+ /** Public path of an entry. Default: `/${model}/${slug}`. */
8
+ path?: (model: string, entry: Record<string, unknown> & {
9
+ id: string;
10
+ locale: string;
11
+ }) => string;
12
+ /** Turn SEO problems in changed fields into warnings for the reviewer. Default true. */
13
+ checks?: boolean;
14
+ }
15
+ export interface SeoIssue {
16
+ level: "error" | "warning" | "tip";
17
+ field?: string;
18
+ message: string;
19
+ }
20
+ /** Score an entry 0–100 with concrete fixes. Pure: works on drafts and published data alike. */
21
+ export declare function auditEntry(model: Model, data: Record<string, any>): {
22
+ score: number;
23
+ issues: SeoIssue[];
24
+ stats: {
25
+ words: number;
26
+ headings: number;
27
+ images: number;
28
+ internalLinks: number;
29
+ titleLength: number;
30
+ descriptionLength: number;
31
+ };
32
+ };
33
+ /** SEO checks for agents and people, plus sitemap.xml and robots.txt. */
34
+ export declare function seo(opts?: SeoOptions): import("../kernel/modules.ts").ModuleDef;