File size: 4,331 Bytes
0cc319d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f1fead
0cc319d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { normalizePost, getByPath, type NormalizedPost, type SiteConfig } from "./sites";

const SiteSchema: z.ZodType<SiteConfig> = z.object({
  id: z.string(),
  name: z.string(),
  baseUrl: z.string().url(),
  searchPath: z.string(),
  params: z.object({ tags: z.string(), page: z.string(), limit: z.string() }),
  postsPath: z.string(),
  fields: z.object({
    id: z.string(),
    previewUrl: z.string(),
    fileUrl: z.string(),
    ext: z.string(),
    tags: z.string(),
    source: z.string().optional(),
    rating: z.string().optional(),
    score: z.string().optional(),
    sampleUrl: z.string().optional(),
    fileSize: z.string().optional(),
    width: z.string().optional(),
    height: z.string().optional(),
    md5: z.string().optional(),
    uploader: z.string().optional(),
    createdAt: z.string().optional(),
  }),

  headers: z.record(z.string(), z.string()).optional(),
  pageStartsAt: z.number().optional(),
});

const InputSchema = z.object({
  site: SiteSchema,
  tags: z.string().default(""),
  page: z.number().int().min(1).default(1),
  limit: z.number().int().min(1).max(69426734621).default(40),
  login: z.string().optional(),
  apiKey: z.string().optional(),
});

export type SearchResult = {
  posts: NormalizedPost[];
  error?: string;
};

export const searchPosts = createServerFn({ method: "POST" })
  .validator((input: unknown) => InputSchema.parse(input))
  .handler(async ({ data }): Promise<SearchResult> => {
    const { site, tags, page, limit, login, apiKey } = data;
    const pageParam = (site.pageStartsAt ?? 1) === 0 ? page - 1 : page;
    const url = new URL(site.searchPath, site.baseUrl);
    url.searchParams.set(site.params.tags, tags);
    url.searchParams.set(site.params.page, String(pageParam));
    url.searchParams.set(site.params.limit, String(limit));

    if (login) {
      url.searchParams.set("login", login);
    }
    if (apiKey) {
      url.searchParams.set("api_key", apiKey);
    }

    const tag = `[searchPosts:${site.id}]`;
    const safeUrl = url.toString().replace(/api_key=[^&]+/, "api_key=***");
    console.log(`${tag} GET ${safeUrl}`);
    try {
      const res = await fetch(url.toString(), {
        headers: {
          Accept: "application/json",
          "User-Agent": "LovableGrabber/1.0",
          ...(site.headers ?? {}),
        },
      });
      console.log(`${tag} status ${res.status} ${res.headers.get("content-type") ?? ""}`);
      if (!res.ok) {
        const body = await res.text().catch(() => "");
        console.error(`${tag} error body: ${body.slice(0, 500)}`);
        return { posts: [], error: `${site.name} returned ${res.status}` };
      }
      let json: unknown;
      try {
        json = await res.json();
      } catch (e) {
        console.error(`${tag} invalid JSON`, e);
        return { posts: [], error: `${site.name} did not return JSON` };
      }
      let arr = getByPath(json, site.postsPath);
      // Sites (like e621 in Nov 2026) may change between {posts:[...]} and a bare array.
      if (!Array.isArray(arr) && Array.isArray(json)) {
        console.warn(`${tag} "${site.postsPath}" not an array; using root array`);
        arr = json;
      }
      if (!Array.isArray(arr) && json && typeof json === "object" && Array.isArray((json as { posts?: unknown }).posts)) {
        console.warn(`${tag} using "posts" fallback`);
        arr = (json as { posts: unknown[] }).posts;
      }
      if (!Array.isArray(arr)) {
        console.error(`${tag} no posts array; top-level keys: ${json && typeof json === "object" ? Object.keys(json).join(",") : typeof json}`);
        return { posts: [], error: `Response at "${site.postsPath}" is not an array` };
      }
      const posts = arr
        .map((raw) => normalizePost(raw, site.fields))
        .filter((p): p is NormalizedPost => p !== null);
      console.log(`${tag} ${arr.length} raw -> ${posts.length} usable posts`);
      if (arr.length && !posts.length) console.warn(`${tag} field mapping matched nothing; sample keys: ${Object.keys(arr[0] ?? {}).join(",")}`);
      return { posts };
    } catch (err) {
      console.error(`${tag} request failed`, err);
      return { posts: [], error: err instanceof Error ? err.message : "Request failed" };
    }
  });