/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export interface ExtractedPageData { url: string; title: string; description?: string; markdown: string; structuredData?: any; tables?: any[]; feedItems?: any[]; links?: string[]; timestamp: string; } export interface OpenApiGeneratorOptions { version?: "3.0.0" | "3.1.0"; baseUrl?: string; } export interface DomainOpenApiOptions { domain: string; title?: string; description?: string; version?: "3.0.0" | "3.1.0"; pages: ExtractedPageData[]; baseUrl?: string; } /** * Infer a JSON Schema (Draft 2020-12 / OpenAPI 3.1 compatible) from a JavaScript object. */ export function inferJsonSchema( obj: any, version: "3.0.0" | "3.1.0" = "3.1.0", ): any { if (obj === null || obj === undefined) { return version === "3.1.0" ? { type: ["string", "null"] } : { type: "string", nullable: true }; } if (typeof obj === "string") { const schema: Record = { type: "string", example: obj.slice(0, 150) }; if (/^https?:\/\/[^\s]+$/i.test(obj)) { schema.format = "uri"; } else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(obj)) { schema.format = "date-time"; } else if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(obj)) { schema.format = "email"; } return schema; } if (typeof obj === "number") { return version === "3.1.0" && Number.isInteger(obj) ? { type: "integer", example: obj } : { type: "number", example: obj }; } if (typeof obj === "boolean") { return { type: "boolean", example: obj }; } if (Array.isArray(obj)) { if (obj.length === 0) { return { type: "array", items: { type: "string" } }; } const itemSchemas = obj.slice(0, 10).map((item) => inferJsonSchema(item, version)); const mergedItemSchema = mergeJsonSchemas(itemSchemas); return { type: "array", items: mergedItemSchema }; } if (typeof obj === "object") { const props: Record = {}; for (const [k, v] of Object.entries(obj)) { const safeKey = k.replace(/[^a-zA-Z0-9_]/g, "_"); props[safeKey] = inferJsonSchema(v, version); } return { type: "object", properties: props, }; } return { type: "string" }; } /** * Merges multiple JSON schemas into a unified object schema. */ export function mergeJsonSchemas( schemas: any[], ): any { if (!schemas || schemas.length === 0) return { type: "object", properties: {} }; if (schemas.length === 1) return schemas[0]; // If all are objects, merge their properties const allObjects = schemas.every((s) => s.type === "object"); if (allObjects) { const mergedProps: Record = {}; for (const s of schemas) { if (s.properties) { for (const [key, val] of Object.entries(s.properties)) { if (!mergedProps[key]) { mergedProps[key] = val; } else { // Merge if both are objects if (mergedProps[key].type === "object" && (val as any).type === "object") { mergedProps[key] = mergeJsonSchemas( [mergedProps[key], val], ); } } } } } return { type: "object", properties: mergedProps, }; } return schemas[0]; } /** * Generate OpenAPI Schema for a single page. * Keeps backward compatibility with 3.0.0 while offering 3.1.0 via options. */ export function generateOpenApiSchema( data: ExtractedPageData, options?: OpenApiGeneratorOptions, ): any { const version = options?.version ?? "3.0.0"; const is31 = version === "3.1.0"; const properties: Record = { url: { type: "string", format: "uri", example: data.url }, title: { type: "string", example: data.title }, description: { type: "string", example: data.description || "" }, markdown: { type: "string", description: "GFM Markdown of the page content", example: data.markdown ? data.markdown.slice(0, 200) : "", }, timestamp: { type: "string", format: "date-time", example: data.timestamp }, }; if (data.links && data.links.length > 0) { properties.links = { type: "array", items: { type: "string", format: "uri" }, example: data.links.slice(0, 5), }; } if (data.structuredData) { properties.structuredData = inferJsonSchema(data.structuredData, version); } if (data.tables && data.tables.length > 0) { properties.tables = { type: "array", items: { type: "object", properties: { caption: { type: "string" }, headers: { type: "array", items: { type: "string" } }, rows: { type: "array", items: { type: "object", additionalProperties: true }, }, }, }, }; } if (data.feedItems && data.feedItems.length > 0) { properties.feedItems = { type: "array", items: inferJsonSchema(data.feedItems[0], version), }; } let pathName = "/"; try { const urlObj = new URL(data.url); pathName = "/" + urlObj.pathname.replace(/^\/|\/$/g, "").replace(/\//g, "_"); if (pathName === "/") pathName = "/root"; } catch { pathName = "/scraped_page"; } const spec: Record = { openapi: version, info: { title: `Bxc Auto-Generated API for ${data.title.slice(0, 50)}`, description: `Dynamically typed OpenAPI representation of crawled page: ${data.url}`, version: "1.0.0", }, paths: { [pathName]: { get: { summary: `Retrieve scraped details of ${data.title.slice(0, 50)}`, description: "Returns the parsed Markdown, metadata, and JSON-LD extracted from the page.", responses: { "200": { description: "Typed structured page content", content: { "application/json": { schema: { type: "object", properties, }, }, }, }, }, }, }, }, }; if (is31) { spec.jsonSchemaDialect = "https://spec.openapis.org/oas/3.1/dialect/base"; } return spec; } /** * Generates an OpenAPI 3.1 schema for a page. */ export function generateOpenApi31Schema( data: ExtractedPageData, options?: Omit, ): any { return generateOpenApiSchema(data, { ...options, version: "3.1.0" }); } /** * Generate a unified Domain-level OpenAPI 3.1 Specification aggregating all crawled pages, * collections, feed items, and data tables into a coherent REST API. */ export function generateDomainOpenApiSchema(options: DomainOpenApiOptions): any { const version = options.version ?? "3.1.0"; const is31 = version === "3.1.0"; const domain = options.domain; const title = options.title ?? `${domain} Live API`; const description = options.description ?? `Autonomous REST API dynamically synthesized from ${options.pages.length} crawled pages of ${domain} by Bxc.`; // Extract all items from feedItems, structured data, and microdata const allItems: any[] = []; const allTables: any[] = []; for (const p of options.pages) { if (p.feedItems && p.feedItems.length > 0) { allItems.push(...p.feedItems); } if (p.tables && p.tables.length > 0) { allTables.push(...p.tables); } if (p.structuredData?.microdata && Array.isArray(p.structuredData.microdata)) { for (const m of p.structuredData.microdata) { if (m.properties) { allItems.push({ ...m.properties, _type: m.type }); } } } } // Infer unified item schema const itemSchemas = allItems.slice(0, 30).map((it) => inferJsonSchema(it, version)); const unifiedItemSchema = allItems.length > 0 ? mergeJsonSchemas(itemSchemas) : { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, url: { type: "string", format: "uri" }, }, }; const pageSummarySchema = { type: "object", properties: { url: { type: "string", format: "uri" }, title: { type: "string" }, description: { type: "string" }, timestamp: { type: "string", format: "date-time" }, textLength: { type: "integer" }, }, }; const paginationSchema = { type: "object", properties: { total: { type: "integer", example: allItems.length }, limit: { type: "integer", example: 20 }, offset: { type: "integer", example: 0 }, hasMore: { type: "boolean", example: false }, }, }; const spec: Record = { openapi: version, info: { title, description, version: "1.0.0", }, servers: [ { url: options.baseUrl ?? `http://localhost:3456`, description: "Local Bxc Site-to-API Live Server", }, ], paths: { "/api/items": { get: { summary: `List structured items extracted from ${domain}`, description: "Returns paginated entity records (products, articles, posts, microdata) with query filtering.", parameters: [ { name: "limit", in: "query", description: "Maximum number of items to return", schema: { type: "integer", default: 20 }, }, { name: "offset", in: "query", description: "Number of items to skip", schema: { type: "integer", default: 0 }, }, { name: "q", in: "query", description: "Search filter across item title and description", schema: { type: "string" }, }, ], responses: { "200": { description: "List of extracted domain items", content: { "application/json": { schema: { type: "object", properties: { items: { type: "array", items: { $ref: "#/components/schemas/Item" }, }, pagination: { $ref: "#/components/schemas/Pagination" }, }, }, }, }, }, }, }, }, "/api/items/{id}": { get: { summary: "Retrieve item by ID or index", parameters: [ { name: "id", in: "path", required: true, description: "Item identifier or index", schema: { type: "string" }, }, ], responses: { "200": { description: "Single structured item detail", content: { "application/json": { schema: { $ref: "#/components/schemas/Item" }, }, }, }, "404": { description: "Item not found", }, }, }, }, "/api/pages": { get: { summary: `List all crawled pages for ${domain}`, parameters: [ { name: "limit", in: "query", schema: { type: "integer", default: 20 }, }, { name: "offset", in: "query", schema: { type: "integer", default: 0 }, }, ], responses: { "200": { description: "List of indexed web pages", content: { "application/json": { schema: { type: "object", properties: { pages: { type: "array", items: { $ref: "#/components/schemas/PageSummary" }, }, pagination: { $ref: "#/components/schemas/Pagination" }, }, }, }, }, }, }, }, }, "/api/tables": { get: { summary: `List extracted tabular datasets from ${domain}`, responses: { "200": { description: "Array of extracted data tables", content: { "application/json": { schema: { type: "object", properties: { tables: { type: "array", items: { type: "object", properties: { caption: { type: "string" }, headers: { type: "array", items: { type: "string" } }, rows: { type: "array", items: { type: "object", additionalProperties: true }, }, }, }, }, }, }, }, }, }, }, }, }, "/api/search": { get: { summary: `Full-text keyword search across crawled content`, parameters: [ { name: "q", in: "query", required: true, description: "Search keywords", schema: { type: "string" }, }, { name: "limit", in: "query", schema: { type: "integer", default: 10 }, }, ], responses: { "200": { description: "Ranked search results from SQLite FTS5 index", content: { "application/json": { schema: { type: "object", properties: { query: { type: "string" }, results: { type: "array", items: { type: "object", properties: { url: { type: "string" }, title: { type: "string" }, snippet: { type: "string" }, rank: { type: "number" }, }, }, }, }, }, }, }, }, }, }, }, "/api/schema": { get: { summary: "Retrieve inferred JSON Schema definition for this site's entities", responses: { "200": { description: "Inferred JSON Schema Draft 2020-12", content: { "application/json": { schema: { type: "object", additionalProperties: true }, }, }, }, }, }, }, }, components: { schemas: { Item: unifiedItemSchema, PageSummary: pageSummarySchema, Pagination: paginationSchema, }, }, }; if (is31) { spec.jsonSchemaDialect = "https://spec.openapis.org/oas/3.1/dialect/base"; } return spec; } /** * Creates an Elysia REST API application exposing the synthesized API endpoints for any indexed domain. */ export async function createSiteToApiServer(options: { domain: string; openapiSpec: any; pages: ExtractedPageData[]; items: any[]; tables?: any[]; dbSearchFn?: (q: string, limit: number) => any[]; }) { const { Elysia } = await import("elysia"); const { cors } = await import("@elysiajs/cors"); const { swagger } = await import("@elysiajs/swagger"); const app = new Elysia() .use(cors()) .use( swagger({ path: "/docs", documentation: { info: options.openapiSpec.info, tags: [{ name: "Site-to-API", description: `Dynamic API for ${options.domain}` }], }, }), ) .get("/openapi.json", () => options.openapiSpec) .get("/api/schema", () => options.openapiSpec.components?.schemas?.Item ?? {}) .get("/api/items", ({ query }: { query: Record }) => { const limit = query.limit ? parseInt(query.limit, 10) : 20; const offset = query.offset ? parseInt(query.offset, 10) : 0; const q = query.q?.toLowerCase(); let filtered = options.items; if (q) { filtered = filtered.filter((item) => { const s = JSON.stringify(item).toLowerCase(); return s.includes(q); }); } const paginated = filtered.slice(offset, offset + limit); return { items: paginated, pagination: { total: filtered.length, limit, offset, hasMore: offset + limit < filtered.length, }, }; }) .get("/api/items/:id", ({ params, set }: { params: { id: string }; set: any }) => { const idx = parseInt(params.id, 10); const found = !isNaN(idx) && options.items[idx] ? options.items[idx] : options.items.find((it) => it.id === params.id || it.url === params.id); if (!found) { set.status = 404; return { error: "Item not found" }; } return found; }) .get("/api/pages", ({ query }: { query: Record }) => { const limit = query.limit ? parseInt(query.limit, 10) : 20; const offset = query.offset ? parseInt(query.offset, 10) : 0; const summaries = options.pages.map((p) => ({ url: p.url, title: p.title, description: p.description || "", timestamp: p.timestamp, textLength: p.markdown ? p.markdown.length : 0, })); return { pages: summaries.slice(offset, offset + limit), pagination: { total: summaries.length, limit, offset, hasMore: offset + limit < summaries.length, }, }; }) .get("/api/tables", () => { return { tables: options.tables ?? [] }; }) .get("/api/search", ({ query }: { query: Record }) => { const q = query.q || ""; const limit = query.limit ? parseInt(query.limit, 10) : 10; if (options.dbSearchFn) { const results = options.dbSearchFn(q, limit); return { query: q, results }; } // In-memory fallback search const qLower = q.toLowerCase(); const matched = options.pages .filter( (p) => p.title.toLowerCase().includes(qLower) || (p.markdown && p.markdown.toLowerCase().includes(qLower)), ) .slice(0, limit) .map((p) => ({ url: p.url, title: p.title, snippet: p.markdown ? p.markdown.slice(0, 200) : "", rank: 1.0, })); return { query: q, results: matched }; }); return app; }