Support sub-path deploy via NEXT_PUBLIC_BASE_PATH (loma.chat/pagiva)

Adds basePath config, withBase/appUrl helpers, base-path-aware cookies,
OAuth redirects, manifest, service worker and cron runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Loma Bot Ops
2026-11-22 16:48:42 +07:00
parent 9d5a029fa5
commit 4a673ebb28
38 changed files with 130 additions and 57 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
@@ -29,7 +30,7 @@ export function AccountForm({ initial }: { initial: { name: string; email: strin
form.set("removeAvatar", String(removeAvatar));
if (file) form.set("avatar", file);
try {
const response = await fetch("/api/account", { method: "PUT", body: form });
const response = await fetch(withBase("/api/account"), { method: "PUT", body: form });
const json = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(json.error ?? "บันทึกไม่สำเร็จ");
toast.show("บันทึกโปรไฟล์แล้ว");
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useEffect, useState } from "react";
import Link from "next/link";
@@ -138,7 +139,7 @@ function BriefForm({
e.preventDefault();
setError(null);
setBusy(true);
const res = await fetch("/api/analysis", {
const res = await fetch(withBase("/api/analysis"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, business, audience, goal, budgetBaht: Number(budget.replace(/,/g, "")), days: Number(days) }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import Link from "next/link";
@@ -40,7 +41,7 @@ export function CaptionAssistant({
const label = "refine" in input ? input.refine : "draft";
setBusy(label);
setError(null);
const res = await fetch("/api/ai/caption", {
const res = await fetch(withBase("/api/ai/caption"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, targets, caption, ...input }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
/* eslint-disable @next/next/no-img-element -- Graph CDN attachment URLs */
import { useCallback, useEffect, useState } from "react";
@@ -49,7 +50,7 @@ export function InboxView({ pageId, pageName, hasInstagram, canReply }: { pageId
const [error, setError] = useState<string | null>(null);
const [sending, setSending] = useState(false);
const base = `/api/inbox/${pageId}/conversations`;
const base = withBase(`/api/inbox/${pageId}/conversations`);
// Fetchers return data; state is only set in their promise callbacks.
const fetchList = useCallback(async (): Promise<{ conversations: Conversation[]; error?: string }> => {
+3 -2
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
@@ -75,7 +76,7 @@ export function LoginForm({ providers }: { providers: Provider[] }) {
e.preventDefault();
setBusy(true);
setError(null);
const res = await fetch("/api/auth/login", {
const res = await fetch(withBase("/api/auth/login"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, remember }),
@@ -92,7 +93,7 @@ export function LoginForm({ providers }: { providers: Provider[] }) {
function socialHref(p: Provider): string {
const q = new URLSearchParams({ from, remember: remember ? "1" : "0" });
return `/api/auth/oauth/${p}/start?${q}`;
return withBase(`/api/auth/oauth/${p}/start?${q}`);
}
return (
+3 -2
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
@@ -42,7 +43,7 @@ interface Member {
}
async function api<T>(url: string, init?: RequestInit): Promise<{ ok: true; data: T } | { ok: false; error: string }> {
const res = await fetch(url, { ...init, headers: { "Content-Type": "application/json" } });
const res = await fetch(withBase(url), { ...init, headers: { "Content-Type": "application/json" } });
const body = await res.json().catch(() => ({}));
return res.ok ? { ok: true, data: body as T } : { ok: false, error: body.error ?? "ทำรายการไม่สำเร็จ" };
}
@@ -211,7 +212,7 @@ export function PagesManager({
<h2>บัญชี Facebook</h2>
{appConfigured ? (
// Full navigation (not <Link>): the start route redirects to facebook.com.
<a href="/api/facebook/oauth/start" className="btn btn-primary btn-sm ml-auto">
<a href={withBase("/api/facebook/oauth/start")} className="btn btn-primary btn-sm ml-auto">
<Icon name="link" size={14} /> {connections.length ? "เชื่อมบัญชีเพิ่ม / ขอสิทธิ์ใหม่" : "เข้าสู่ระบบด้วย Facebook"}
</a>
) : (
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import { Icon } from "./Icon";
@@ -28,7 +29,7 @@ export function PostCheck({ pageId, caption, targets, hasImage }: { pageId: stri
async function run() {
setBusy(true);
setError(null);
const res = await fetch("/api/ai/check", {
const res = await fetch(withBase("/api/ai/check"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, caption, targets, hasImage }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
/* eslint-disable @next/next/no-img-element -- Blob URLs and Graph CDN images, not optimisable */
import { useRef, useState } from "react";
@@ -124,7 +125,7 @@ export function PostEditor({
setBusy(label);
setError(null);
try {
const res = await fetch(url, { ...init, headers: init.body instanceof FormData ? undefined : { "Content-Type": "application/json" } });
const res = await fetch(withBase(url), { ...init, headers: init.body instanceof FormData ? undefined : { "Content-Type": "application/json" } });
const body = await res.json().catch(() => ({}));
if (!res.ok) {
setError(body.error ?? "ทำรายการไม่สำเร็จ");
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import { useRouter } from "next/navigation";
@@ -29,7 +30,7 @@ export function ProfileForm({
const [error, setError] = useState<string | null>(null);
async function request(path: string, method: string, body?: ShopProfile) {
const res = await fetch(path, { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null);
const res = await fetch(withBase(path), { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null);
const json = res ? await res.json().catch(() => ({})) : {};
return { ok: Boolean(res?.ok), json };
}
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import { useRouter } from "next/navigation";
@@ -12,7 +13,7 @@ export function RefreshInsightsButton({ pageId, variant = "on-band" }: { pageId:
async function refresh() {
setBusy(true);
const res = await fetch("/api/insights/refresh", {
const res = await fetch(withBase("/api/insights/refresh"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId }),
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import Link from "next/link";
@@ -15,7 +16,7 @@ export function ReplyDrafts({ pageId, conversationId, onPick }: { pageId: string
async function draft() {
setBusy(true);
setError(null);
const res = await fetch("/api/ai/reply", {
const res = await fetch(withBase("/api/ai/reply"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, conversationId }),
+4 -3
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import { useRouter } from "next/navigation";
@@ -41,7 +42,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd
if (!editing) return;
setBusy(true);
setError(null);
const res = await fetch("/api/reply-rules", {
const res = await fetch(withBase("/api/reply-rules"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...editing, pageId, keywords: keywordsText }),
@@ -54,7 +55,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd
}
async function toggle(rule: Rule) {
await fetch("/api/reply-rules", {
await fetch(withBase("/api/reply-rules"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...rule, pageId, isActive: !rule.isActive }),
@@ -64,7 +65,7 @@ export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEd
async function remove(rule: Rule) {
if (!window.confirm(`ลบกฎ "${rule.name}"?`)) return;
await fetch(`/api/reply-rules?id=${rule.id}`, { method: "DELETE" });
await fetch(withBase(`/api/reply-rules?id=${rule.id}`), { method: "DELETE" });
router.refresh();
}
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useEffect } from "react";
@@ -6,7 +7,7 @@ import { useEffect } from "react";
export function ServiceWorker() {
useEffect(() => {
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
navigator.serviceWorker.register("/sw.js").catch((e) => console.error("[sw] register failed", e));
navigator.serviceWorker.register(withBase("/sw.js"), { scope: withBase("/") }).catch((e) => console.error("[sw] register failed", e));
}, []);
return null;
}
+3 -2
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
@@ -127,7 +128,7 @@ export function Shell({
}
async function logout() {
await fetch("/api/auth/logout", { method: "POST" });
await fetch(withBase("/api/auth/logout"), { method: "POST" });
router.replace("/login");
router.refresh();
}
@@ -162,7 +163,7 @@ export function Shell({
<div className="flex items-center gap-3 px-1.5 pb-2">
<span className="w-9 h-9 rounded-[10px] overflow-hidden shrink-0 shadow-sm">
{/* eslint-disable-next-line @next/next/no-img-element -- generated app icon route */}
<img src="/icons/192" alt="" width={36} height={36} />
<img src={withBase("/icons/192")} alt="" width={36} height={36} />
</span>
<div className="leading-tight flex-1 min-w-0">
<div className="font-bold">ระบบจัดการเพจ</div>
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import { useRouter } from "next/navigation";
@@ -29,7 +30,7 @@ export function UsersManager({ users, currentUserId }: { users: UserRow[]; curre
setBusy(true);
setError(null);
setFlash(null);
const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const res = await fetch(withBase(url), { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const data = await res.json().catch(() => ({}));
setBusy(false);
if (!res.ok) {
+2 -1
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import Link from "next/link";
import { useState } from "react";
@@ -41,7 +42,7 @@ export function WeekBoard({ week, today, posts, tray, editablePageIds, nextId }:
if (busy || !post || !canMove(post) || post.day === day) return;
setBusy(true);
try {
const res = await fetch(`/api/posts/${id}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "plan", plannedAt: day ? bkkMidnight(day).toISOString() : null }) });
const res = await fetch(withBase(`/api/posts/${id}`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "plan", plannedAt: day ? bkkMidnight(day).toISOString() : null }) });
const body = await res.json();
if (!res.ok) throw new Error(body.error ?? "วางวันไม่สำเร็จ");
toast.show(day ? "วางวันแล้ว · ยังไม่ได้ตั้งเวลาเผยแพร่" : "ย้ายกลับคิวที่ยังไม่วางแผนแล้ว");
+3 -2
View File
@@ -1,4 +1,5 @@
"use client";
import { withBase } from "@/lib/base-path";
import { useState } from "react";
import Link from "next/link";
@@ -36,7 +37,7 @@ export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId
async function plan() {
setBusy("plan");
setError(null);
const res = await fetch("/api/ai/week-plan", {
const res = await fetch(withBase("/api/ai/week-plan"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, week, goal, count }),
@@ -56,7 +57,7 @@ export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId
let created = 0;
let firstError: string | null = null;
for (const p of chosen) {
const res = await fetch("/api/posts", {
const res = await fetch(withBase("/api/posts"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pageId, title: p.title, caption: p.caption, targets: ["FACEBOOK"], aiAssisted: true, plannedAt: bkkMidnight(p.day).toISOString() }),