@jini-ai/search 0.7.3-next.1 → 0.7.3-next.3

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.
@@ -0,0 +1,75 @@
1
+ import { defineJsonRoute, ok, routeReply } from '@jini-ai/core/contracts/server';
2
+ import { parseSearchRequest } from '../../../http-query.js';
3
+ function searchQueryErrorMessage({ issue, limits }, _optional = {}) {
4
+ switch (issue.code) {
5
+ case 'not-single': return `'${issue.field}' must be given once`;
6
+ case 'text-required': return "'q' is required";
7
+ case 'text-too-long': return `'q' must be at most ${limits.maxTextLength} characters`;
8
+ case 'invalid-collections': return `'collection' must be up to ${limits.maxCollections} comma-separated names like 'post'`;
9
+ case 'invalid-limit': return `'limit' must be an integer from 1 to ${limits.maxLimit}`;
10
+ case 'invalid-cursor': return "'cursor' must be the nextCursor of a previous page";
11
+ }
12
+ }
13
+ /** The service result as the public JSON contract. */
14
+ function searchReply({ result }, _optional = {}) {
15
+ if (result.status === 'invalid')
16
+ return routeReply({ status: 400, body: { error: 'invalid_request', message: result.message } });
17
+ if (result.status === 'unavailable')
18
+ return routeReply({ status: 503, body: { error: 'search_unavailable', reason: result.reason } });
19
+ return {
20
+ hits: result.page.hits.map(hit => ({ url: hit.url, title: hit.title, snippet: hit.snippet, highlights: hit.highlights, collection: hit.key.collection })),
21
+ nextCursor: result.page.nextCursor ?? null,
22
+ };
23
+ }
24
+ /**
25
+ * One search: session audiences after the runtime is ready, the provider query, the bucketed event.
26
+ * A rejection is not caught here; the mount's error port answers it.
27
+ * @complexity Per request: one member-session read, one provider query and one access check.
28
+ */
29
+ async function runSearch({ runtime, deps, query }, _optional = {}) {
30
+ await runtime.ready;
31
+ const sessionToken = deps.sessionToken();
32
+ const audiences = await runtime.audiencesForSession(sessionToken === undefined ? {} : { sessionToken });
33
+ const { siteId, workspaceId } = runtime;
34
+ const clock = deps.clock;
35
+ const startedAt = clock?.nowMs();
36
+ const result = await runtime.service.query({ siteId, workspaceId, query }, { audiences });
37
+ if (result.status === 'ok')
38
+ deps.recordSearchPerformed({ properties: {
39
+ resultCountBucket: searchResultCountBucket({ count: result.page.hits.length }),
40
+ ...(startedAt === undefined || !clock ? {} : { durationBucket: searchDurationBucket({ elapsedMs: clock.nowMs() - startedAt }) }),
41
+ } });
42
+ return searchReply({ result });
43
+ }
44
+ /** `GET /api/search`; mount it with request-bound `sessionToken` / `recordSearchPerformed` deps. */
45
+ export const siteSearchRoute = {
46
+ ...defineJsonRoute({
47
+ method: 'get',
48
+ path: '/api/search',
49
+ parse: ({ query }) => ok({ value: query }),
50
+ handle: async ({ input, deps }) => {
51
+ const parsed = parseSearchRequest({ query: input, limits: deps.limits });
52
+ if ('error' in parsed)
53
+ return ok({ value: routeReply({ status: 400, body: { error: 'invalid_request', message: searchQueryErrorMessage({ issue: parsed.error, limits: deps.limits }) } }) });
54
+ const runtime = deps.siteSearch;
55
+ if (!runtime)
56
+ return ok({ value: routeReply({ status: 503, body: { error: 'search_unavailable', reason: 'not_configured' } }) });
57
+ return ok({ value: await runSearch({ runtime, deps, query: parsed.query }) });
58
+ },
59
+ }),
60
+ responseHeaders: { 'Cache-Control': 'private, no-store' },
61
+ };
62
+ function searchResultCountBucket({ count }, _optional = {}) {
63
+ if (count === 0)
64
+ return '0';
65
+ return count <= 10 ? '1-10' : '11-50';
66
+ }
67
+ /** Coarse latency only; query terms and exact timing never enter the event. @complexity O(1). */
68
+ function searchDurationBucket({ elapsedMs }, _optional = {}) {
69
+ if (elapsedMs < 100)
70
+ return '<100ms';
71
+ if (elapsedMs < 1000)
72
+ return '100ms-1s';
73
+ return '>=1s';
74
+ }
75
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @file The fail-closed last check before a search hit is shown (`@jini-ai/search`'s
3
+ * `SearchAccessPort`) for the CMS's posts and pages. A provider's index may lag the database; this
4
+ * re-reads the rows the hits name, in one query per collection, and keeps only the keys that are
5
+ * live right now and, when member-gated, open to one of the viewer's audiences.
6
+ *
7
+ * Fails closed: a key of another site or workspace, of an unknown collection, of a missing,
8
+ * draft, trashed or still-scheduled row, or with an unreadable gate is never visible.
9
+ */
10
+ import type { Kysely } from "kysely";
11
+ import type { StorageKernel } from "@jini-ai/core/contracts/storage";
12
+ import type { SearchAccessPort } from "../ports.js";
13
+ /** The member-context fields search reads; the host's member context satisfies it structurally. */
14
+ type SearchMemberContext = {
15
+ readonly isAuthenticated: boolean;
16
+ readonly activeTierIds: readonly string[];
17
+ readonly isPaid: boolean;
18
+ };
19
+ import { type CmsSearchRules } from "./cms-document-source.js";
20
+ /**
21
+ * A viewer's search audiences, from their validated member context (never from request input):
22
+ * none for an anonymous viewer, otherwise `members`, `paid` when entitled, and one token per tier.
23
+ * Uses the same tokens `cmsSearchVisibility` writes, so the two cannot drift apart.
24
+ * @complexity O(a) in the active tier count.
25
+ */
26
+ export declare function memberSearchAudiences(required: {
27
+ context: SearchMemberContext;
28
+ }, _optional?: Record<string, never>): string[];
29
+ /**
30
+ * The access port over one site's content database. Generic over the host's schema `DB`: the host
31
+ * kernel is borrowed through the `posts` slice search reads.
32
+ * @example createCmsSearchAccessPort({ kernel, now, isLiveAt, resolveMemberAccess }).visibleKeys({ siteId, keys, audiences })
33
+ * @complexity visibleKeys: one indexed query per collection present among the keys, O(k) work.
34
+ */
35
+ export declare function createCmsSearchAccessPort<DB>(required: {
36
+ readonly kernel: StorageKernel<Kysely<DB>, DB>;
37
+ readonly now: () => number;
38
+ } & CmsSearchRules, optional?: {
39
+ readonly collections?: readonly string[];
40
+ }): SearchAccessPort;
41
+ export {};
42
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1,63 @@
1
+ import { encodeSearchKey } from "../contract.js";
2
+ import { CMS_SEARCH_COLLECTIONS, MEMBER_AUDIENCE, cmsSearchVisibility, isRowLive, toNowIso, } from "./cms-document-source.js";
3
+ /**
4
+ * A viewer's search audiences, from their validated member context (never from request input):
5
+ * none for an anonymous viewer, otherwise `members`, `paid` when entitled, and one token per tier.
6
+ * Uses the same tokens `cmsSearchVisibility` writes, so the two cannot drift apart.
7
+ * @complexity O(a) in the active tier count.
8
+ */
9
+ export function memberSearchAudiences(required, _optional = {}) {
10
+ const { context } = required;
11
+ if (!context.isAuthenticated)
12
+ return [];
13
+ return [MEMBER_AUDIENCE.members, ...(context.isPaid ? [MEMBER_AUDIENCE.paid] : []), ...context.activeTierIds.map((tierId) => MEMBER_AUDIENCE.tier({ tierId }))];
14
+ }
15
+ /** Whether a gated row is open to any of `audiences`. @complexity O(r·a), both small. */
16
+ function audienceAllows({ memberAccessJson, audiences, resolveMemberAccess }, _optional = {}) {
17
+ const visibility = cmsSearchVisibility({ memberAccessJson, resolveMemberAccess });
18
+ return visibility.kind === "public" || visibility.audiences.some(audience => audiences.includes(audience));
19
+ }
20
+ /** Keys grouped by known collection; keys of other sites and unknown collections are dropped here.
21
+ * @complexity O(k). */
22
+ function groupKeys({ siteId, keys, collections }, _optional = {}) {
23
+ const groups = new Map();
24
+ for (const key of keys) {
25
+ const collection = key.collection;
26
+ if (key.siteId !== siteId || !collections.includes(collection))
27
+ continue;
28
+ groups.set(collection, [...(groups.get(collection) ?? []), key]);
29
+ }
30
+ return groups;
31
+ }
32
+ /**
33
+ * The access port over one site's content database. Generic over the host's schema `DB`: the host
34
+ * kernel is borrowed through the `posts` slice search reads.
35
+ * @example createCmsSearchAccessPort({ kernel, now, isLiveAt, resolveMemberAccess }).visibleKeys({ siteId, keys, audiences })
36
+ * @complexity visibleKeys: one indexed query per collection present among the keys, O(k) work.
37
+ */
38
+ export function createCmsSearchAccessPort(required, optional = {}) {
39
+ const { now, isLiveAt, resolveMemberAccess } = required;
40
+ const kernel = required.kernel;
41
+ const collections = optional.collections ?? CMS_SEARCH_COLLECTIONS;
42
+ return {
43
+ async visibleKeys({ siteId, keys, audiences }) {
44
+ const nowIso = toNowIso({ nowMs: now() });
45
+ const visible = new Set();
46
+ for (const [collection, group] of groupKeys({ siteId, keys, collections })) {
47
+ const rows = await kernel.run(db => db.selectFrom("posts")
48
+ .select(["id", "workspace_id", "status", "publish_at", "deleted_at", "member_access_json"])
49
+ .where("kind", "=", collection).where("id", "in", group.map(key => key.documentId)).execute());
50
+ const byId = new Map(rows.map(row => [row.id, row]));
51
+ for (const key of group) {
52
+ const row = byId.get(key.documentId);
53
+ // The workspace is part of the key: a hit can never borrow another workspace's row.
54
+ if (row?.workspace_id !== key.workspaceId || !isRowLive({ row, nowIso, isLiveAt }) || !audienceAllows({ memberAccessJson: row.member_access_json, audiences, resolveMemberAccess }))
55
+ continue;
56
+ visible.add(encodeSearchKey({ key }));
57
+ }
58
+ }
59
+ return visible;
60
+ },
61
+ };
62
+ }
63
+ //# sourceMappingURL=access.js.map
@@ -0,0 +1,137 @@
1
+ /**
2
+ * @file The CMS's posts and pages as `@jini-ai/search` document sources (collections `post` and
3
+ * `page`, the two `kind`s of the bespoke `posts` table). The generic indexer never trusts an event:
4
+ * it asks {@link SearchDocumentSource.load} for the row's current truth, and this file is that truth.
5
+ *
6
+ * What may be indexed is exactly what the public site shows: `isLiveAt` (published, not trashed,
7
+ * past its go-live time — `contracts/core/scheduled-publish.ts`). Everything else loads as
8
+ * `document: null`, which the indexer turns into a tombstone.
9
+ *
10
+ * Bespoke HTML page edits: `SqlPagesHtmlDocumentStore.write` (and its doc→html conversion) does not
11
+ * go through `post.ts`, so it enqueues the same `entry.updated` itself (its `outbox` dep). Without it
12
+ * such an edit reached the index only through a backfill/reindex `scan`, never through `load` on an
13
+ * event — and the backfill watermark is complete after the first pass, so never again.
14
+ *
15
+ * The host owns the publish rule, the public URL, the text extraction and the member-gate decoding;
16
+ * it passes each in as a required field (see this folder's README, `## Wiring`).
17
+ */
18
+ import type { Kysely, Selectable } from "kysely";
19
+ import type { StorageKernel } from "@jini-ai/core/contracts/storage";
20
+ import type { PublicPostKind } from "@jini-ai/core/contracts/site/cms-core";
21
+ import type { SearchVisibility } from "../contract.js";
22
+ import type { SearchDocumentSource } from "../ports.js";
23
+ /** The `posts` columns search reads: a local structural slice of the host's table. */
24
+ export interface CmsSearchPostsTable {
25
+ id: string;
26
+ workspace_id: string;
27
+ kind: string;
28
+ slug: string;
29
+ status: string;
30
+ updated_at: string;
31
+ version: number;
32
+ publish_at: string | null;
33
+ deleted_at: string | null;
34
+ member_access_json: string | null;
35
+ }
36
+ /** The slice of the host database search queries. */
37
+ export interface CmsSearchDatabase {
38
+ posts: CmsSearchPostsTable;
39
+ }
40
+ export type CmsSearchPostRow = Selectable<CmsSearchPostsTable>;
41
+ /** The host kernel seen through {@link CmsSearchDatabase}; no connection work. */
42
+ export type CmsSearchKernel = StorageKernel<Kysely<CmsSearchDatabase>, CmsSearchDatabase>;
43
+ /** A whole host `posts` row (`selectAll` returns every column of the host's table). */
44
+ export type CmsHostPostRow<DB> = DB extends {
45
+ posts: infer Table;
46
+ } ? Selectable<Table> : never;
47
+ /** The host's publish rule over a row's raw columns (published, not trashed, past its go-live time). */
48
+ export type CmsSearchIsLiveAt = (required: {
49
+ record: {
50
+ readonly status: string;
51
+ readonly publishAt?: string | null;
52
+ readonly deletedAt?: string | null;
53
+ };
54
+ nowIso: string;
55
+ }) => boolean;
56
+ /** A decoded member gate. */
57
+ export interface CmsMemberAccess {
58
+ readonly visibility: string;
59
+ readonly tierIds?: readonly string[];
60
+ }
61
+ /** The host's decoder of a row's raw `member_access_json` (fails open to `public` only for a never-gated row). */
62
+ export type CmsSearchResolveMemberAccess = (required: {
63
+ raw: string | null;
64
+ }) => CmsMemberAccess;
65
+ /** The host rules both the document sources and the access port apply. */
66
+ export interface CmsSearchRules {
67
+ readonly isLiveAt: CmsSearchIsLiveAt;
68
+ readonly resolveMemberAccess: CmsSearchResolveMemberAccess;
69
+ }
70
+ /** The host collaborators the document sources need beyond {@link CmsSearchRules}. */
71
+ export interface CmsSearchDocumentRules<DB> extends CmsSearchRules {
72
+ /** The site-relative URL the public site routes a post's slug to. */
73
+ readonly postPublicPath: (required: {
74
+ slug: string;
75
+ }) => string;
76
+ /** Plain-text title and body of a row (the host's post FTS projection's extraction). */
77
+ readonly toSearchText: (required: {
78
+ row: CmsHostPostRow<DB>;
79
+ }) => {
80
+ readonly title: string;
81
+ readonly bodyText: string;
82
+ };
83
+ }
84
+ /** The events `post.ts` emits on a public-facing status transition (`classifyStatusTransition`).
85
+ * Trashing a published row emits `entry.unpublished`, so trash needs no event of its own. */
86
+ export declare const CMS_SEARCH_EVENTS: readonly ["entry.published", "entry.updated", "entry.unpublished"];
87
+ export declare const CMS_SEARCH_COLLECTIONS: readonly PublicPostKind[];
88
+ /**
89
+ * Audience tokens for member-gated entries. A viewer's audiences are built from the same tokens by
90
+ * `memberSearchAudiences` (`access.ts`); prefixed so a tier id can never spell `members` or `paid`.
91
+ */
92
+ export declare const MEMBER_AUDIENCE: {
93
+ readonly members: "members";
94
+ readonly paid: "paid";
95
+ readonly tier: ({ tierId }: {
96
+ tierId: string;
97
+ }, _optional?: {}) => string;
98
+ };
99
+ /**
100
+ * Who may see an entry, from its raw `member_access_json`. Mirrors `DefaultMemberAccessResolver.decide`:
101
+ * a never-gated row is public; `tiers` with no tier ids and any malformed/unknown visibility become
102
+ * restricted to no audience at all (fail closed, never public).
103
+ * @complexity O(t) in the tier-id count.
104
+ */
105
+ export declare function cmsSearchVisibility(required: {
106
+ memberAccessJson: string | null;
107
+ resolveMemberAccess: CmsSearchResolveMemberAccess;
108
+ }, _optional?: Record<string, never>): SearchVisibility;
109
+ /** The ISO instant `isLiveAt` compares `publishAt` against. */
110
+ export declare const toNowIso: ({ nowMs }: {
111
+ nowMs: number;
112
+ }, _optional?: {}) => string;
113
+ /** Whether a stored row is publicly visible right now (`isLiveAt` on its raw columns). @complexity O(1). */
114
+ export declare function isRowLive({ row, nowIso, isLiveAt }: {
115
+ row: Pick<CmsSearchPostRow, "status" | "publish_at" | "deleted_at">;
116
+ nowIso: string;
117
+ isLiveAt: CmsSearchIsLiveAt;
118
+ }, _optional?: {}): boolean;
119
+ /** @complexity O(1). */
120
+ export declare function cmsSearchRevision(required: {
121
+ row: Pick<CmsSearchPostRow, "updated_at" | "publish_at" | "version"> | null;
122
+ live: boolean;
123
+ occurredAtMs: number;
124
+ }, _optional?: Record<string, never>): number;
125
+ /**
126
+ * The `post` and `page` sources over one site's content database (one workspace per content.db).
127
+ * Generic over the host's schema `DB`: the host kernel is borrowed through {@link CmsSearchDatabase}.
128
+ * @example registerMany(SEARCH_DOCUMENT_SOURCES, createCmsSearchDocumentSources({ kernel, now, isLiveAt, resolveMemberAccess, postPublicPath, toSearchText }))
129
+ * @complexity O(1) to build.
130
+ */
131
+ export declare function createCmsSearchDocumentSources<DB>(required: {
132
+ readonly kernel: StorageKernel<Kysely<DB>, DB>;
133
+ readonly now: () => number;
134
+ } & CmsSearchDocumentRules<DB>, optional?: {
135
+ readonly collections?: readonly string[];
136
+ }): SearchDocumentSource[];
137
+ //# sourceMappingURL=cms-document-source.d.ts.map
@@ -0,0 +1,136 @@
1
+ /** The events `post.ts` emits on a public-facing status transition (`classifyStatusTransition`).
2
+ * Trashing a published row emits `entry.unpublished`, so trash needs no event of its own. */
3
+ export const CMS_SEARCH_EVENTS = ["entry.published", "entry.updated", "entry.unpublished"];
4
+ export const CMS_SEARCH_COLLECTIONS = ["post", "page"];
5
+ /**
6
+ * Audience tokens for member-gated entries. A viewer's audiences are built from the same tokens by
7
+ * `memberSearchAudiences` (`access.ts`); prefixed so a tier id can never spell `members` or `paid`.
8
+ */
9
+ export const MEMBER_AUDIENCE = { members: "members", paid: "paid", tier: ({ tierId }, _optional = {}) => `tier:${tierId}` };
10
+ /**
11
+ * Who may see an entry, from its raw `member_access_json`. Mirrors `DefaultMemberAccessResolver.decide`:
12
+ * a never-gated row is public; `tiers` with no tier ids and any malformed/unknown visibility become
13
+ * restricted to no audience at all (fail closed, never public).
14
+ * @complexity O(t) in the tier-id count.
15
+ */
16
+ export function cmsSearchVisibility(required, _optional = {}) {
17
+ const access = required.resolveMemberAccess({ raw: required.memberAccessJson });
18
+ switch (access.visibility) {
19
+ case "public": return { kind: "public" };
20
+ case "members": return { kind: "restricted", audiences: [MEMBER_AUDIENCE.members] };
21
+ case "paid": return { kind: "restricted", audiences: [MEMBER_AUDIENCE.paid] };
22
+ case "tiers": return { kind: "restricted", audiences: (Array.isArray(access.tierIds) ? access.tierIds : []).map((tierId) => MEMBER_AUDIENCE.tier({ tierId })) };
23
+ default: return { kind: "restricted", audiences: [] };
24
+ }
25
+ }
26
+ /** The ISO instant `isLiveAt` compares `publishAt` against. */
27
+ export const toNowIso = ({ nowMs }, _optional = {}) => new Date(nowMs).toISOString();
28
+ /** Whether a stored row is publicly visible right now (`isLiveAt` on its raw columns). @complexity O(1). */
29
+ export function isRowLive({ row, nowIso, isLiveAt }, _optional = {}) {
30
+ return isLiveAt({ record: { status: row.status, publishAt: row.publish_at, deletedAt: row.deleted_at }, nowIso });
31
+ }
32
+ /**
33
+ * Search revisions. Every write the indexer makes must carry a revision strictly greater than the
34
+ * last one for its key, tombstones included, or the provider ignores it as stale. Hence:
35
+ *
36
+ * - The instant is epoch ms, scaled by 1000 with `version % 1000` added: `version` grows on every
37
+ * save (reverts too, INV-04), so two saves in the same millisecond still order. 1000 saves of one
38
+ * row inside one millisecond cannot happen, and the result stays a safe integer until ~2255.
39
+ * - A LIVE row's instant is `max(updatedAt, publishAt)`. A scheduled post was tombstoned while
40
+ * embargoed (its `entry.published` fires at go-live, owned by the go-live fix), and that
41
+ * tombstone's instant is at most the event time, which precedes `publishAt`; so going live
42
+ * outranks it with no new save. A live revision depends on the row alone: a replayed event
43
+ * re-derives the same number and is harmlessly stale.
44
+ * - A NOT-LIVE row's instant is `max(updatedAt, occurredAt)`, so the tombstone outranks the last
45
+ * indexed revision even when the event that removed it is newer than the row's own timestamp.
46
+ * - A MISSING row (permanently deleted) uses `occurredAt` with the top tie-break, outranking every
47
+ * revision of that millisecond.
48
+ */
49
+ const scaled = ({ instantMs, tieBreak }, _optional = {}) => instantMs * 1000 + tieBreak;
50
+ const ms = ({ iso }, _optional = {}) => (iso === null ? 0 : Date.parse(iso));
51
+ /** @complexity O(1). */
52
+ export function cmsSearchRevision(required, _optional = {}) {
53
+ const { row, live, occurredAtMs } = required;
54
+ if (row === null)
55
+ return scaled({ instantMs: occurredAtMs, tieBreak: 999 });
56
+ const instant = Math.max(ms({ iso: row.updated_at }), live ? ms({ iso: row.publish_at }) : occurredAtMs);
57
+ return scaled({ instantMs: instant, tieBreak: row.version % 1000 });
58
+ }
59
+ /** The indexable document for a live row. Title and body are plain text (the post FTS projection's
60
+ * own extraction, TipTap and bespoke-HTML alike); the URL is the one the public site routes. */
61
+ function toDocument(required) {
62
+ const { siteId, collection, row, revision, rules } = required;
63
+ // `selectAll` read every host column; the slice type only names the ones this file uses.
64
+ const text = rules.toSearchText({ row: row });
65
+ return {
66
+ key: { siteId, workspaceId: row.workspace_id, collection, documentId: row.id },
67
+ revision,
68
+ url: rules.postPublicPath({ slug: row.slug }),
69
+ title: text.title,
70
+ body: text.bodyText,
71
+ visibility: cmsSearchVisibility({ memberAccessJson: row.member_access_json, resolveMemberAccess: rules.resolveMemberAccess }),
72
+ };
73
+ }
74
+ /** A row's current truth for the index. @complexity O(body size) for the text extraction. */
75
+ function toSourceRecord(required) {
76
+ const { siteId, workspaceId, collection, documentId, nowMs, occurredAtMs, rules } = required;
77
+ // A row of the other kind is not a document of this collection: treat it as missing here.
78
+ const row = required.row?.kind === collection ? required.row : null;
79
+ const live = row !== null && isRowLive({ row, nowIso: toNowIso({ nowMs }), isLiveAt: rules.isLiveAt });
80
+ const revision = cmsSearchRevision({ row, live, occurredAtMs });
81
+ const key = { siteId, workspaceId, collection, documentId };
82
+ return { key, revision, document: live ? toDocument({ siteId, collection, row, revision, rules }) : null };
83
+ }
84
+ /** The document id an event names for `collection`: post.ts's payload `{ entryId, contentType }`.
85
+ * Generic `entries` emit the same event names without `contentType`, so they are never claimed. */
86
+ function documentIdFor(event, collection) {
87
+ if (!CMS_SEARCH_EVENTS.includes(event.name))
88
+ return null;
89
+ const payload = (typeof event.payload === "object" && event.payload !== null ? event.payload : {});
90
+ return payload.contentType === collection && typeof payload.entryId === "string" ? payload.entryId : null;
91
+ }
92
+ /** One collection's source. @complexity load: one primary-key read; scan: one keyset page. */
93
+ function createSource(required) {
94
+ const { kernel, now, collection, rules } = required;
95
+ return {
96
+ collection,
97
+ events: CMS_SEARCH_EVENTS,
98
+ documentIdOf: ({ event }) => documentIdFor(event, collection),
99
+ async load({ siteId, workspaceId, documentId, occurredAtMs }) {
100
+ const row = await kernel.run(db => db.selectFrom("posts").selectAll()
101
+ .where("workspace_id", "=", workspaceId).where("id", "=", documentId).executeTakeFirst());
102
+ return toSourceRecord({ siteId, workspaceId, collection, documentId, row: row ?? null, nowMs: now(), occurredAtMs, rules });
103
+ },
104
+ async scan({ siteId, workspaceId, limit }, optional = {}) {
105
+ const nowMs = now();
106
+ const nowIso = toNowIso({ nowMs });
107
+ const rows = await kernel.run(db => {
108
+ let query = db.selectFrom("posts").selectAll()
109
+ .where("workspace_id", "=", workspaceId).where("kind", "=", collection)
110
+ .where("status", "=", "published").where("deleted_at", "is", null)
111
+ // Same rule as `isLiveAt`: ISO UTC strings compare in time order.
112
+ .where(eb => eb.or([eb("publish_at", "is", null), eb("publish_at", "<=", nowIso)]));
113
+ if (optional.cursor !== undefined)
114
+ query = query.where("id", ">", optional.cursor);
115
+ // Keyset on the primary key: stable under concurrent writes, never repeats or skips a row.
116
+ return query.orderBy("id", "asc").limit(limit).execute();
117
+ });
118
+ const records = rows.map(row => toSourceRecord({ siteId, workspaceId, collection, documentId: row.id, row, nowMs, occurredAtMs: nowMs, rules }));
119
+ const last = rows.at(-1);
120
+ // A short (or empty) page is the last one; a full page may have more after its last id.
121
+ return last === undefined || rows.length < limit ? { records } : { records, nextCursor: last.id };
122
+ },
123
+ };
124
+ }
125
+ /**
126
+ * The `post` and `page` sources over one site's content database (one workspace per content.db).
127
+ * Generic over the host's schema `DB`: the host kernel is borrowed through {@link CmsSearchDatabase}.
128
+ * @example registerMany(SEARCH_DOCUMENT_SOURCES, createCmsSearchDocumentSources({ kernel, now, isLiveAt, resolveMemberAccess, postPublicPath, toSearchText }))
129
+ * @complexity O(1) to build.
130
+ */
131
+ export function createCmsSearchDocumentSources(required, optional = {}) {
132
+ const { kernel, now, ...rules } = required;
133
+ const slice = kernel;
134
+ return (optional.collections ?? CMS_SEARCH_COLLECTIONS).map(collection => createSource({ kernel: slice, now, collection, rules }));
135
+ }
136
+ //# sourceMappingURL=cms-document-source.js.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * @file The site-search indexer's bookkeeping on the host's content database: one Kysely
3
+ * body for SQLite, PGlite and Postgres, behind this package's `SearchIndexStatePort` and
4
+ * `SearchTargetPort`. No search logic here: the generic indexer decides, this only stores.
5
+ *
6
+ * The two ports are returned as two objects because both name a `get` with different inputs.
7
+ *
8
+ * The four tables are host-owned: the host names them (`tables`) and creates them. `kysely` is a
9
+ * type-only import here, so the host's Kysely instance is the only runtime dependency.
10
+ */
11
+ import type { StorageKernel } from "@jini-ai/core/contracts/storage";
12
+ import type { Kysely } from "kysely";
13
+ import type { SearchIndexStatePort, SearchTargetPort } from "../ports.js";
14
+ /** Numbers stored as `bigint` come back as a number (SQLite), a string or a bigint (Postgres drivers). */
15
+ type Big = number | string | bigint;
16
+ interface StateTable {
17
+ site_id: string;
18
+ provider_id: string;
19
+ generation: number;
20
+ doc_key: string;
21
+ workspace_id: string;
22
+ collection: string;
23
+ document_id: string;
24
+ revision: Big;
25
+ deleted: number;
26
+ status: string;
27
+ attempts: number;
28
+ task_id: string | null;
29
+ last_error: string | null;
30
+ updated_at_ms: Big;
31
+ }
32
+ interface WatermarkTable {
33
+ site_id: string;
34
+ provider_id: string;
35
+ generation: number;
36
+ collection: string;
37
+ cursor: string | null;
38
+ done: number;
39
+ }
40
+ interface RetiredTable {
41
+ site_id: string;
42
+ provider_id: string;
43
+ generation: number;
44
+ retired_at_ms: Big;
45
+ }
46
+ interface TargetTable {
47
+ site_id: string;
48
+ active_provider_id: string | null;
49
+ active_generation: number | null;
50
+ building_provider_id: string | null;
51
+ building_generation: number | null;
52
+ updated_at_ms: Big;
53
+ }
54
+ /** The three bookkeeping tables plus the retired generations. They are host-managed raw SQL, so the
55
+ * host's generated database type never holds them; this local shape is what the queries are typed
56
+ * against. The keys are type-level names only: the host's real table names arrive in `tables`. */
57
+ export interface SearchIndexDatabase {
58
+ search_index_state: StateTable;
59
+ search_index_watermarks: WatermarkTable;
60
+ search_index_targets: TargetTable;
61
+ search_index_retired: RetiredTable;
62
+ }
63
+ /** Host-owned table names, quoted by Kysely; no product table defaults live in the adapter. */
64
+ export interface SearchIndexTables {
65
+ state: string;
66
+ watermarks: string;
67
+ targets: string;
68
+ retired: string;
69
+ }
70
+ export interface SqlSearchIndexStore {
71
+ readonly indexState: SearchIndexStatePort;
72
+ readonly targets: SearchTargetPort;
73
+ }
74
+ /**
75
+ * The SQL search-index store on one content database.
76
+ * @example const { indexState, targets } = createSqlSearchIndexStore({ kernel, now: clock.nowMs, tables });
77
+ * @complexity O(1) to build; see each half for per-call cost.
78
+ */
79
+ export declare function createSqlSearchIndexStore(required: {
80
+ readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
81
+ readonly now: () => number;
82
+ readonly tables: SearchIndexTables;
83
+ }, _optional?: Record<string, never>): SqlSearchIndexStore;
84
+ export {};
85
+ //# sourceMappingURL=index-state-store.d.ts.map