reboot alterflixhub

This commit is contained in:
Bkk1234 committed 2026-11-01 17:24:44 +07:00
commit 1e84023a44
188 files changed
+31629

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
import type {
AgentLoopFinalResponseGuardContext,
AgentLoopFinalResponseGuardResult,
} from "@agent-native/core/server";
const DOMAIN_OPERATION_PATTERN =
/\b(create|add|make|build|update|edit|delete|remove|list|show|open|save|publish|submit|send|export|import)\b/i;
const EXPLICIT_EXTEND_APP_PATTERN =
/\b(extend (this |the )?app|add (a |the )?(feature|capability|page|route|screen|action|ui)|scaffold|implement (a |the )?(feature|app)|wire up|build (this |the )?app|new action|create (a |an )?action|agent-native|defineAction)\b/i;
const SOURCE_HANDOFF_PATTERN =
/\b(actions\/|app\/|server\/|drizzle\/|schema\.ts|\.tsx|source code|source files?|edit the (file|code)|I'll (create|add|update|modify|write)|I will (create|add|update|modify|write)|let me (create|add|update|modify|write)|pnpm action)\b/i;
const APP_ACTION_PREFIXES = [
"create-",
"update-",
"delete-",
"list-",
"get-",
"add-",
"remove-",
"export-",
"import-",
"patch-",
"search-",
"preview-",
"navigate",
"view-screen",
] as const;
const RETRY_MESSAGE =
"The user asked to operate on app data or domain objects. Before editing source or proposing a code change, call tool-search with a specific query for their request, then call the matching registered app action if one exists. Only extend source when no registered action can complete the request.";
function latestUserText(
messages: AgentLoopFinalResponseGuardContext["messages"],
): string {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message?.role !== "user") continue;
const content = message.content;
if (typeof content === "string") return content;
if (!Array.isArray(content)) continue;
return content
.filter(
(part): part is { type: "text"; text: string } =>
!!part &&
typeof part === "object" &&
(part as { type?: string }).type === "text" &&
typeof (part as { text?: string }).text === "string",
)
.map((part) => part.text)
.join("\n");
}
return "";
}
function looksLikeDomainOperationRequest(text: string): boolean {
const trimmed = text.trim();
if (!trimmed || EXPLICIT_EXTEND_APP_PATTERN.test(trimmed)) return false;
return DOMAIN_OPERATION_PATTERN.test(trimmed);
}
function calledToolSearch(
toolCalls: AgentLoopFinalResponseGuardContext["toolCalls"],
): boolean {
return toolCalls.some((call) => call.name === "tool-search");
}
function calledAppFacingTool(
toolCalls: AgentLoopFinalResponseGuardContext["toolCalls"],
): boolean {
return toolCalls.some((call) => {
if (APP_ACTION_PREFIXES.some((prefix) => call.name.startsWith(prefix))) {
return true;
}
if (call.name !== "bash") return false;
const command = String(
(call.input as { command?: string } | undefined)?.command ?? "",
);
return /\bpnpm action\b/.test(command);
});
}
function usedSourceEditTools(
toolCalls: AgentLoopFinalResponseGuardContext["toolCalls"],
): boolean {
return toolCalls.some((call) =>
["bash", "read", "edit", "write", "grep"].includes(call.name),
);
}
function proposesSourceHandoff(text: string): boolean {
return SOURCE_HANDOFF_PATTERN.test(text);
}
export function appOperationFinalResponseGuard(
context: AgentLoopFinalResponseGuardContext,
): AgentLoopFinalResponseGuardResult | null {
if (context.executionMode === "plan") return null;
const requestText = context.requestText ?? latestUserText(context.messages);
if (!looksLikeDomainOperationRequest(requestText)) return null;
if (calledToolSearch(context.toolCalls)) return null;
if (calledAppFacingTool(context.toolCalls)) return null;
if (
!proposesSourceHandoff(context.text) &&
!usedSourceEditTools(context.toolCalls)
) {
return null;
}
return {
retryMessage: RETRY_MESSAGE,
expandToolSurface: true,
maxRetries: 1,
};
}
+30
View File
@@ -0,0 +1,30 @@
// App data layer — the DB client lives here.
//
// This starter ships without any tables, so the wiring is stubbed out. `getDb()`
// returns a Drizzle client bound to the app's `schema`. Enable it when you add
// your first table (see `drizzle/START_HERE.md`):
//
// 1. Define tables in `drizzle/schema.ts`.
// 2. Uncomment the lines below, run `pnpm db:generate`, then `pnpm db:migrate`
// to apply the new migration. (drizzle-orm, drizzle-kit, drizzle.config.ts,
// and the db:generate/db:migrate scripts already ship.)
//
// import { createGetDb } from "@agent-native/core/db";
// import { registerShareableResource } from "@agent-native/core/sharing";
// import * as schema from "../drizzle/schema";
//
// export const getDb = createGetDb(schema);
// export { schema };
//
// // Lets accessFilter/assertAccess and the share actions resolve "note" rows.
// registerShareableResource({
// type: "note",
// resourceTable: schema.notes,
// sharesTable: schema.noteShares,
// displayName: "Note",
// titleColumn: "title",
// getResourcePath: (note) => `/notes/${note.id}`,
// getDb,
// });
export {};
+31
View File
@@ -0,0 +1,31 @@
import { fileURLToPath } from "node:url";
import {
loadTemplateMcpConformance,
providerSchemaViolations,
templateMcpCatalogModes,
type TemplateMcpConformance,
} from "@agent-native/core/testing";
import { beforeAll, describe, expect, it } from "vitest";
const projectRoot = fileURLToPath(new URL("..", import.meta.url));
describe("Chat MCP catalogs", () => {
let template: TemplateMcpConformance;
beforeAll(async () => {
template = await loadTemplateMcpConformance(projectRoot);
}, 180_000);
it.each(templateMcpCatalogModes(projectRoot))(
"advertises only schemas that pass every pinned provider rule in the %s catalog",
async (mode) => {
const tools = await template.listCatalog(mode);
expect(tools.length).toBeGreaterThan(0);
expect(tools.flatMap((tool) => providerSchemaViolations(tool))).toEqual(
[],
);
},
60_000,
);
});
+6
View File
@@ -0,0 +1,6 @@
import { runAuthGuard } from "@agent-native/core/server";
import { defineEventHandler } from "h3";
export default defineEventHandler(async (event) => {
return runAuthGuard(event);
});
+24
View File
@@ -0,0 +1,24 @@
import { getOrgContext } from "@agent-native/core/org";
import {
createAgentChatPlugin,
loadActionsFromStaticRegistry,
} from "@agent-native/core/server";
import actionsRegistry from "../../.generated/actions-registry.js";
import { appOperationFinalResponseGuard } from "../agent/app-operation-guard.js";
export default createAgentChatPlugin({
appId: "app",
actions: loadActionsFromStaticRegistry(actionsRegistry),
mcp: { connectorCatalog: [] },
nativeActionsInDev: true,
finalResponseGuard: appOperationFinalResponseGuard,
resolveOrgId: async (event) => (await getOrgContext(event)).orgId,
systemPrompt: `You are this app's agent. Help the user inspect, explain, and extend the app.
Use actions as the source of truth. Inspect the current screen when context matters. Treat requests to create, add, build, update, delete, or otherwise operate on the app's domain objects as app operations, not source-code changes. Call the matching app action directly. If an expected action is not loaded, use tool-search before considering a source-code handoff. Only hand off a request as a code change when it changes the app's capabilities, UI, or behavior and no registered action can complete it.
When asked to extend the app, keep the change small and agent-native: add or update actions, put real product UI on the page, and keep application state and navigation visible to the agent.
Do not add i18n catalogs or changelog/What's New surfaces unless the user explicitly asks.`,
});
@@ -0,0 +1,14 @@
import { defineAppConfig } from "@agent-native/core/server";
export default defineAppConfig({
app: {
// This name appears in transactional emails. Change it to your product name.
name: "App",
// The source template keeps a renamed app from inheriting first-party email branding.
sourceTemplate: "builder-code-starter",
// Keep the template's authenticated entry explicit after renaming the app.
homePath: "/home",
// Optional: use your own absolute HTTPS logo URL in transactional emails.
// logoUrl: "https://example.com/logo.png",
},
});
+8
View File
@@ -0,0 +1,8 @@
import { createAuthPlugin } from "@agent-native/core/server";
// Email/password auth with optional Google OAuth (enabled automatically when
// GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are set). No marketing copy — a
// blank app defines its own brand on the login page when it needs one by setting loginHtml in this config.
export default createAuthPlugin({
rootAuth: false, // auth is not serverd on / by default
});
+15
View File
@@ -0,0 +1,15 @@
import { defineAppConfig } from "@agent-native/core/server";
// Refuse opt-in default plugins so a blank app doesn't boot Slack/Telegram/etc
// integration routes, Sentry error tracking, the PTY terminal, or agent
// long-term memory. `plugins.disabled` is read from getAppConfig() (this `app`
// layer), which is why it must live here and not in agent-native.json.
// Never disable agent-chat/auth/core-routes — they carry most of the app.
export default defineAppConfig({
plugins: {
disabled: ["integrations", "observational-memory", "sentry", "terminal"],
},
app: {
homePath: "/",
},
});
+6
View File
@@ -0,0 +1,6 @@
import { defineNitroPlugin } from "@agent-native/core/server";
import { startAgentNativeOtel } from "@agent-native/otel";
export default defineNitroPlugin(() => {
startAgentNativeOtel();
});
+24
View File
@@ -0,0 +1,24 @@
import { defineEventHandler, setResponseHeader } from "h3";
import { createH3SSRHandler } from "@agent-native/core/server/ssr-handler";
/**
* ค่าเริ่มต้นของ framework ตั้ง `geolocation=()` ซึ่งบล็อก navigator.geolocation
* ทั้งเอกสาร (เบราว์เซอร์ไม่ขึ้น prompt ด้วยซ้ำ) — เปิดให้ first-party เท่านั้น
* ส่วน directive อื่นคงค่าเดิมของ core ไว้
*
* ตั้ง header ที่ route handler เพราะ handler รันหลัง security middleware ของ core
* (ย้ายไป server/plugins แล้ว ค่าถูกเขียนทับทั้งแบบ bootstrap และ first-request)
*/
const PERMISSIONS_POLICY =
"camera=*, microphone=(self), geolocation=(self), screen-wake-lock=()";
const renderPage = createH3SSRHandler(
() => import("virtual:react-router/server-build"),
);
export default defineEventHandler(async (event) => {
const response = await renderPage(event);
setResponseHeader(event, "Permissions-Policy", PERMISSIONS_POLICY);
return response;
});
+13
View File
@@ -0,0 +1,13 @@
import { defineEventHandler, getQuery } from "h3";
import { requireAdmin } from "@/lib/admin-auth.server";
import { readEvents, summarize } from "@/lib/analytics.server";
/** สรุปสถิติการค้นหา — ใช้ในแท็บ "สถิติการค้นหา" ของหลังบ้าน */
export default defineEventHandler(async (event) => {
requireAdmin(event);
const query = getQuery(event);
const requested = Number(query.days);
const days = [1, 7, 30, 90].includes(requested) ? requested : 7;
return summarize(await readEvents(), days);
});
@@ -0,0 +1,41 @@
import { createError, defineEventHandler, readBody } from "h3";
import { requireAdmin } from "@/lib/admin-auth.server";
import { readContent, sanitizeCinemas, writeContent } from "@/lib/content.server";
/**
* วาง JSON ของโรงหนัง (ออบเจกต์เดียวหรือ array) เพื่อเพิ่ม/ทับรายการเดิม
* ใช้กับปุ่ม "วาง JSON" ในหน้า admin — ทับเฉพาะ slug ที่ซ้ำกัน
*/
export default defineEventHandler(async (event) => {
requireAdmin(event);
const body = (await readBody(event)) as { raw?: string };
const raw = (body?.raw ?? "").trim();
if (!raw) {
throw createError({ statusCode: 400, statusMessage: "ยังไม่มีข้อมูลให้วาง" });
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (error) {
throw createError({
statusCode: 400,
statusMessage: `JSON ไม่ถูกต้อง: ${error instanceof Error ? error.message : ""}`,
});
}
const incoming = sanitizeCinemas(Array.isArray(parsed) ? parsed : [parsed]);
const current = await readContent();
const bySlug = new Map(current.cinemas.map((cinema) => [cinema.slug, cinema]));
for (const cinema of incoming) bySlug.set(cinema.slug, cinema);
const next = {
cinemas: Array.from(bySlug.values()),
site: current.site,
about: current.about,
};
await writeContent(next);
return { imported: incoming.length, store: next };
});
+9
View File
@@ -0,0 +1,9 @@
import { defineEventHandler } from "h3";
import { requireAdmin } from "@/lib/admin-auth.server";
import { readContent } from "@/lib/content.server";
export default defineEventHandler(async (event) => {
requireAdmin(event);
return readContent();
});
+41
View File
@@ -0,0 +1,41 @@
import { createError, defineEventHandler, readBody } from "h3";
import { requireAdmin } from "@/lib/admin-auth.server";
import {
readContent,
sanitizeAbout,
sanitizeCinemas,
sanitizeSite,
writeContent,
} from "@/lib/content.server";
/** บันทึกทั้งชุด: ส่งมาเฉพาะส่วนที่แก้ได้ (cinemas, site และ/หรือ about) */
export default defineEventHandler(async (event) => {
requireAdmin(event);
const body = (await readBody(event)) as {
cinemas?: unknown;
site?: unknown;
about?: unknown;
};
const current = await readContent();
try {
const next = {
cinemas:
body?.cinemas === undefined
? current.cinemas
: sanitizeCinemas(body.cinemas),
site: body?.site === undefined ? current.site : sanitizeSite(body.site),
about:
body?.about === undefined ? current.about : sanitizeAbout(body.about),
};
await writeContent(next);
return next;
} catch (error) {
throw createError({
statusCode: 400,
statusMessage:
error instanceof Error ? error.message : "ข้อมูลไม่ถูกต้อง",
});
}
});
+22
View File
@@ -0,0 +1,22 @@
import { createError, defineEventHandler, readBody } from "h3";
import { createAdminSession, isValidCredentials } from "@/lib/admin-auth.server";
export default defineEventHandler(async (event) => {
const body = (await readBody(event)) as {
username?: string;
password?: string;
};
const username = (body?.username ?? "").trim();
const password = body?.password ?? "";
if (!isValidCredentials(username, password)) {
throw createError({
statusCode: 401,
statusMessage: "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง",
});
}
createAdminSession(event);
return { ok: true };
});
+8
View File
@@ -0,0 +1,8 @@
import { defineEventHandler } from "h3";
import { clearAdminSession, isAdmin } from "@/lib/admin-auth.server";
export default defineEventHandler((event) => {
clearAdminSession(event);
return { ok: true, authenticated: false, wasAuthenticated: isAdmin(event) };
});
+7
View File
@@ -0,0 +1,7 @@
import { defineEventHandler } from "h3";
import { isAdmin } from "@/lib/admin-auth.server";
export default defineEventHandler((event) => ({
authenticated: isAdmin(event),
}));
@@ -0,0 +1,80 @@
import { createHash } from "node:crypto";
import { defineEventHandler, getHeader, getRequestIP, readBody } from "h3";
import { appendEvent } from "@/lib/analytics.server";
import type { AnalyticsEvent, AnalyticsEventType } from "@/lib/analytics-types";
const ALLOWED_TYPES: AnalyticsEventType[] = [
"search",
"cinema_select",
"cinema_view",
"near_me",
];
const MAX_EVENTS_PER_REQUEST = 20;
const MAX_TEXT = 120;
function text(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim().slice(0, MAX_TEXT);
return trimmed === "" ? undefined : trimmed;
}
function count(value: unknown): number | undefined {
const parsed = Number(value);
return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : undefined;
}
/** เกลือหมุนรายวัน — hash ของผู้เข้าชมจึงย้อนระบุตัวตนไม่ได้ */
function visitorHash(ip: string, userAgent: string): string {
const salt = `${new Date().toISOString().slice(0, 10)}${
process.env.ANALYTICS_SALT ?? "alterflixhub-analytics"
}`;
return createHash("sha256").update(`${salt}|${ip}|${userAgent}`).digest("hex").slice(0, 16);
}
/**
* ตัวรับ event ฝั่งเว็บ (เทียบเท่า /api/send ของ Umami)
* ไม่เก็บคุกกี้ ไม่เก็บ IP ดิบ — เก็บเฉพาะ hash ที่หมุนเกลือทุกวัน
*/
export default defineEventHandler(async (event) => {
const body = (await readBody(event)) as
| { events?: unknown }
| Record<string, unknown>;
const rawEvents = Array.isArray(body)
? body
: Array.isArray((body as { events?: unknown })?.events)
? ((body as { events: unknown[] }).events)
: [body];
const ip = getRequestIP(event, { xForwardedFor: true }) ?? "0.0.0.0";
const userAgent = getHeader(event, "user-agent") ?? "";
const visitor = visitorHash(ip, userAgent);
const at = new Date().toISOString();
const accepted: AnalyticsEvent[] = [];
for (const raw of rawEvents.slice(0, MAX_EVENTS_PER_REQUEST)) {
if (!raw || typeof raw !== "object") continue;
const entry = raw as Record<string, unknown>;
const type = entry.type;
if (typeof type !== "string" || !ALLOWED_TYPES.includes(type as AnalyticsEventType)) {
continue;
}
accepted.push({
type: type as AnalyticsEventType,
at,
visitor,
locale: text(entry.locale) ?? "th",
query: text(entry.query),
category: text(entry.category),
result_count: count(entry.result_count),
slug: text(entry.slug),
source: text(entry.source),
position: count(entry.position),
});
}
for (const item of accepted) await appendEvent(item);
return { ok: true, stored: accepted.length };
});
+2
View File
@@ -0,0 +1,2 @@
// Nitro's [...page] catch-all doesn't match "/", and this starter serves its home page at "/".
export { default } from "./[...page].get.js";