@jini-ai/search 0.7.3-next.2 → 0.7.4

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.
package/README.md CHANGED
@@ -15,8 +15,29 @@ results through the composition tokens.
15
15
  | `@jini-ai/search` | universal | The contract (`SearchProvider`, documents, keys, revisions, tombstones), host ports, the `SearchService`/`SearchIndexer` APIs, `createSearchProviderRegistry`, `validateSearchProvider`, and the tokens `SearchProviderRegistryToken`, `SearchServiceToken`, `SearchIndexerToken`, `SearchDocumentSourceToken` (many). |
16
16
  | `@jini-ai/search/tools` | universal | Agent tools over a `SearchService`. |
17
17
  | `@jini-ai/search/contribution` | node | `defineSearchProviderContribution({ filename, define })` for plugin-contributed providers: search owns the manifest parser, the restricted-content refusal and the manifest-id check; the host passes `define` (`spec => defineProviderContribution(spec, recovery)` from `@jini-ai/agent-plugins/lifecycle`), and offers the loaded result to that package's `contributeProviders`. |
18
+ | `@jini-ai/search/site/index-state-store` | node | `createSqlSearchIndexStore({ kernel, now, tables })` returns `{ indexState, targets }`: SQL `SearchIndexStatePort` and `SearchTargetPort` over four host-created tables (state, watermarks, targets, retired) whose names the host injects. One Kysely body for SQLite, PGlite and Postgres; `kysely` is an optional, type-only peer. |
18
19
  | `@jini-ai/search/testkit` | universal | `runSearchProviderConformance`, the in-memory reference provider, and fakes (`createFakeHttpClient`, `createUnavailableHttpClient`, `createInMemorySearchState`, `createStaticAccessPort`, `createPredicateAccessPort`). Test-only. |
19
20
 
21
+ ## Wiring
22
+
23
+ **Site settings** (`@jini-ai/search/site/settings`): `ensureSearchProviderSetting` takes the settings
24
+ ledger's registrar as `deps.ensureSettingDefinitions` (`EnsureSettingDefinitionsPort`) and
25
+ `readSearchProviderSetting` takes its reader as `getEffective` (`GetEffectivePort`) on the existing
26
+ required args; the host binds both from `@jini-ai/core/settings`. `writeSearchProviderSetting` takes
27
+ the host settings write as `writeSetting`. See
28
+ [`DR-005`](../../docs/decisions/DR-005-portable-package-boundaries.md).
29
+
30
+ **CMS document sources and access port** (`@jini-ai/search/site/cms-document-source`,
31
+ `@jini-ai/search/site/access`): `createCmsSearchDocumentSources` and `createCmsSearchAccessPort` borrow
32
+ the host kernel (`StorageKernel<Kysely<DB>, DB>`, generic over the host schema) through a local
33
+ structural slice of the `posts` table (`CmsSearchDatabase`, the columns the queries read; `kysely` is a
34
+ type-only peer). The host rules are required fields on the same args object: `isLiveAt` (the public
35
+ site's publish rule) and `resolveMemberAccess` (the raw `member_access_json` decoder) on both, plus
36
+ `postPublicPath` and `toSearchText` (plain-text title and body of a whole host row) on the sources.
37
+ `cmsSearchVisibility` and `isRowLive` take the same rule on their args. The host binds all four once
38
+ and spreads them into both calls. See
39
+ [`DR-005`](../../docs/decisions/DR-005-portable-package-boundaries.md).
40
+
20
41
  ## Plugin providers
21
42
 
22
43
  A plugin ships a manifest at its package root, under the filename the host chooses:
@@ -4,12 +4,13 @@ import type { SearchIndexerRequired } from './indexer.js';
4
4
  import { type createIndexerResolve, type createIndexerWriteToTarget } from './indexer-write.js';
5
5
  type Watermark = Awaited<ReturnType<SearchIndexStatePort['getWatermark']>>;
6
6
  /** Scan one source from its watermark, writing each page; the watermark moves after EVERY page. */
7
- export declare function createIndexerScanSource({ state, scanPageSize }: {
7
+ export declare function createIndexerScanSource({ state, scanPageSize, dependencies }: {
8
8
  state: SearchIndexStatePort;
9
9
  scanPageSize: number;
10
- }, dependencies: () => {
11
- writeToTarget: ReturnType<typeof createIndexerWriteToTarget>;
12
- }): (input: {
10
+ dependencies: () => {
11
+ writeToTarget: ReturnType<typeof createIndexerWriteToTarget>;
12
+ };
13
+ }, _optional?: Record<string, never>): (input: {
13
14
  source: SearchDocumentSource;
14
15
  target: SearchTarget;
15
16
  siteId: string;
@@ -27,12 +28,13 @@ export declare function createIndexerScanSource({ state, scanPageSize }: {
27
28
  * failed, keep the old generation serving queries until a retry succeeds. It is dropped only
28
29
  * after the atomic flip.
29
30
  */
30
- export declare function createIndexerPromote({ targets, state }: {
31
+ export declare function createIndexerPromote({ targets, state, dependencies }: {
31
32
  targets: SearchTargetPort;
32
33
  state: SearchIndexStatePort;
33
- }, dependencies: () => {
34
- dropRetired: ReturnType<typeof createIndexerDropRetired>;
35
- }): (siteId: string, workspaceId: string, target: SearchTarget) => Promise<boolean>;
34
+ dependencies: () => {
35
+ dropRetired: ReturnType<typeof createIndexerDropRetired>;
36
+ };
37
+ }, _optional?: Record<string, never>): (siteId: string, workspaceId: string, target: SearchTarget) => Promise<boolean>;
36
38
  /**
37
39
  * Drop every retired (replaced) generation of a site. The bookkeeping rows are deleted either
38
40
  * way, since a replaced target is never written or read again. The vendor index can be dropped
@@ -41,17 +43,19 @@ export declare function createIndexerPromote({ targets, state }: {
41
43
  * outcome, a missing credential or an unregistered provider leaves it for the next reconcile,
42
44
  * instead of leaving the old content in the vendor index forever.
43
45
  */
44
- export declare function createIndexerDropRetired({ targets, state }: {
46
+ export declare function createIndexerDropRetired({ targets, state, dependencies }: {
45
47
  targets: SearchTargetPort;
46
48
  state: SearchIndexStatePort;
47
- }, dependencies: () => {
48
- resolve: ReturnType<typeof createIndexerResolve>;
49
- }): (siteId: string, workspaceId: string) => Promise<void>;
50
- export declare function createIndexerBackfillTarget({ sources }: {
49
+ dependencies: () => {
50
+ resolve: ReturnType<typeof createIndexerResolve>;
51
+ };
52
+ }, _optional?: Record<string, never>): (siteId: string, workspaceId: string) => Promise<void>;
53
+ export declare function createIndexerBackfillTarget({ sources, dependencies }: {
51
54
  sources: SearchIndexerRequired['sources'];
52
- }, dependencies: () => {
53
- scanSource: ReturnType<typeof createIndexerScanSource>;
54
- }): (input: {
55
+ dependencies: () => {
56
+ scanSource: ReturnType<typeof createIndexerScanSource>;
57
+ };
58
+ }, _optional?: Record<string, never>): (input: {
55
59
  siteId: string;
56
60
  workspaceId: string;
57
61
  target: SearchTarget;
@@ -65,14 +69,15 @@ export declare function createIndexerReadMarks({ sources, state }: {
65
69
  sources: SearchIndexerRequired['sources'];
66
70
  state: SearchIndexStatePort;
67
71
  }): (target: SearchTarget) => Promise<Watermark[]>;
68
- export declare function createIndexerBackfill({ targets }: {
72
+ export declare function createIndexerBackfill({ targets, dependencies }: {
69
73
  targets: SearchTargetPort;
70
- }, dependencies: () => {
71
- resolve: ReturnType<typeof createIndexerResolve>;
72
- promote: ReturnType<typeof createIndexerPromote>;
73
- backfillTarget: ReturnType<typeof createIndexerBackfillTarget>;
74
- readMarks: ReturnType<typeof createIndexerReadMarks>;
75
- }): SearchIndexer['backfill'];
74
+ dependencies: () => {
75
+ resolve: ReturnType<typeof createIndexerResolve>;
76
+ promote: ReturnType<typeof createIndexerPromote>;
77
+ backfillTarget: ReturnType<typeof createIndexerBackfillTarget>;
78
+ readMarks: ReturnType<typeof createIndexerReadMarks>;
79
+ };
80
+ }, _optional?: Record<string, never>): SearchIndexer['backfill'];
76
81
  export declare function createIndexerStartRebuild({ targets }: {
77
82
  targets: SearchTargetPort;
78
83
  }): SearchIndexer['startRebuild'];
@@ -2,7 +2,7 @@ import {} from './api.js';
2
2
  import {} from './ports.js';
3
3
  import { guarded } from './indexer-write.js';
4
4
  /** Scan one source from its watermark, writing each page; the watermark moves after EVERY page. */
5
- export function createIndexerScanSource({ state, scanPageSize }, dependencies) {
5
+ export function createIndexerScanSource({ state, scanPageSize, dependencies }, _optional = {}) {
6
6
  return async (input) => {
7
7
  const { writeToTarget } = dependencies();
8
8
  const { source, target } = input;
@@ -28,7 +28,7 @@ export function createIndexerScanSource({ state, scanPageSize }, dependencies) {
28
28
  * failed, keep the old generation serving queries until a retry succeeds. It is dropped only
29
29
  * after the atomic flip.
30
30
  */
31
- export function createIndexerPromote({ targets, state }, dependencies) {
31
+ export function createIndexerPromote({ targets, state, dependencies }, _optional = {}) {
32
32
  return async (siteId, workspaceId, target) => {
33
33
  const { dropRetired } = dependencies();
34
34
  const counts = await state.counts({ target });
@@ -51,19 +51,19 @@ export function createIndexerPromote({ targets, state }, dependencies) {
51
51
  * outcome, a missing credential or an unregistered provider leaves it for the next reconcile,
52
52
  * instead of leaving the old content in the vendor index forever.
53
53
  */
54
- export function createIndexerDropRetired({ targets, state }, dependencies) {
54
+ export function createIndexerDropRetired({ targets, state, dependencies }, _optional = {}) {
55
55
  return async (siteId, workspaceId) => {
56
56
  const { resolve } = dependencies();
57
57
  for (const retired of await targets.listRetired({ siteId })) {
58
58
  await state.deleteTarget({ target: retired });
59
59
  const resolved = await resolve(retired, workspaceId);
60
- const dropped = resolved ? await guarded(() => resolved.provider.dropIndex(resolved.ctx)) : null;
60
+ const dropped = resolved ? await guarded({ call: () => resolved.provider.dropIndex(resolved.ctx) }) : null;
61
61
  if (dropped?.status === 'ok')
62
62
  await targets.forgetRetired({ target: retired });
63
63
  }
64
64
  };
65
65
  }
66
- export function createIndexerBackfillTarget({ sources }, dependencies) {
66
+ export function createIndexerBackfillTarget({ sources, dependencies }, _optional = {}) {
67
67
  return async (input) => {
68
68
  const { scanSource } = dependencies();
69
69
  let written = 0;
@@ -89,7 +89,7 @@ export function createIndexerReadMarks({ sources, state }) {
89
89
  return marks;
90
90
  };
91
91
  }
92
- export function createIndexerBackfill({ targets }, dependencies) {
92
+ export function createIndexerBackfill({ targets, dependencies }, _optional = {}) {
93
93
  const operation = async ({ siteId, workspaceId }, { pageBudget = 10 } = {}) => {
94
94
  const { resolve, promote, backfillTarget, readMarks } = dependencies();
95
95
  const current = await targets.get({ siteId });
@@ -101,7 +101,7 @@ export function createIndexerBackfill({ targets }, dependencies) {
101
101
  return { done: false, written: 0, promoted: false };
102
102
  const marks = await readMarks(target);
103
103
  // A fresh target (no source started yet) gets its index created before the very first page.
104
- if (marks.every(mark => mark === null) && (await guarded(() => resolved.provider.ensureIndex(resolved.ctx))).status !== 'ok') {
104
+ if (marks.every(mark => mark === null) && (await guarded({ call: () => resolved.provider.ensureIndex(resolved.ctx) })).status !== 'ok') {
105
105
  return { done: false, written: 0, promoted: false };
106
106
  }
107
107
  const { done, written } = await backfillTarget({ siteId, workspaceId, target, pageBudget, marks });
@@ -16,10 +16,12 @@ export declare function createIndexerSettledRow({ now }: {
16
16
  * only lands while the row still holds this revision AND this task: an event that wrote a newer
17
17
  * revision while the task was awaited keeps its own pending task (and its retry) intact.
18
18
  */
19
- export declare function createIndexerSettleTask(dependencies: () => {
20
- settleObserved: ReturnType<typeof createIndexerSettleObserved>;
21
- settledRow: ReturnType<typeof createIndexerSettledRow>;
22
- }): (row: SearchIndexStateRow, resolved: Resolved, { taskId, awaitTask }: {
19
+ export declare function createIndexerSettleTask({ dependencies }: {
20
+ dependencies: () => {
21
+ settleObserved: ReturnType<typeof createIndexerSettleObserved>;
22
+ settledRow: ReturnType<typeof createIndexerSettledRow>;
23
+ };
24
+ }, _optional?: Record<string, never>): (row: SearchIndexStateRow, resolved: Resolved, { taskId, awaitTask }: {
23
25
  taskId: string;
24
26
  awaitTask: NonNullable<SearchProvider["awaitTask"]>;
25
27
  }) => Promise<number>;
@@ -28,51 +30,60 @@ export declare function createIndexerSettleTask(dependencies: () => {
28
30
  * marked indexed; anything else is returned for a re-load and re-write (never blindly marked
29
31
  * failed: an `unknown` outcome may well have happened).
30
32
  */
31
- export declare function createIndexerCheckRevisions(dependencies: () => {
32
- checkChunk: ReturnType<typeof createIndexerCheckChunk>;
33
- }): (rows: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
33
+ export declare function createIndexerCheckRevisions({ dependencies }: {
34
+ dependencies: () => {
35
+ checkChunk: ReturnType<typeof createIndexerCheckChunk>;
36
+ };
37
+ }, _optional?: Record<string, never>): (rows: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
34
38
  settled: number;
35
39
  rewrite: SearchIndexStateRow[];
36
40
  }>;
37
41
  /** One `revisionOf` call's worth of {@link checkRevisions}; an indeterminate answer leaves the rows as they are. */
38
- export declare function createIndexerCheckChunk(dependencies: () => {
39
- settleObserved: ReturnType<typeof createIndexerSettleObserved>;
40
- settledRow: ReturnType<typeof createIndexerSettledRow>;
41
- }): (chunk: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
42
+ export declare function createIndexerCheckChunk({ dependencies }: {
43
+ dependencies: () => {
44
+ settleObserved: ReturnType<typeof createIndexerSettleObserved>;
45
+ settledRow: ReturnType<typeof createIndexerSettledRow>;
46
+ };
47
+ }, _optional?: Record<string, never>): (chunk: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
42
48
  settled: number;
43
49
  rewrite: SearchIndexStateRow[];
44
50
  }>;
45
51
  /** `pending` rows with a task are awaited; `unknown` rows (and a `pending` row whose process died
46
52
  * between marking and the call, so it has no task) are checked with `revisionOf`. */
47
- export declare function createIndexerSettleInFlight(dependencies: () => {
48
- settleTask: ReturnType<typeof createIndexerSettleTask>;
49
- checkRevisions: ReturnType<typeof createIndexerCheckRevisions>;
50
- }): (rows: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
53
+ export declare function createIndexerSettleInFlight({ dependencies }: {
54
+ dependencies: () => {
55
+ settleTask: ReturnType<typeof createIndexerSettleTask>;
56
+ checkRevisions: ReturnType<typeof createIndexerCheckRevisions>;
57
+ };
58
+ }, _optional?: Record<string, never>): (rows: readonly SearchIndexStateRow[], resolved: Resolved) => Promise<{
51
59
  settled: number;
52
60
  rewrite: SearchIndexStateRow[];
53
61
  }>;
54
62
  /** Re-load the row's document from its source and write the current truth again (a retry). */
55
- export declare function createIndexerRewriteRow({ sources, now }: {
63
+ export declare function createIndexerRewriteRow({ sources, now, dependencies }: {
56
64
  sources: SearchIndexerRequired['sources'];
57
65
  now: SearchIndexerRequired['now'];
58
- }, dependencies: () => {
59
- settleObserved: ReturnType<typeof createIndexerSettleObserved>;
60
- writeToTarget: ReturnType<typeof createIndexerWriteToTarget>;
61
- settledRow: ReturnType<typeof createIndexerSettledRow>;
62
- }): (row: SearchIndexStateRow, workspaceId: string) => Promise<number>;
63
- export declare function createIndexerReconcileTarget({ state, maxAttempts }: {
66
+ dependencies: () => {
67
+ settleObserved: ReturnType<typeof createIndexerSettleObserved>;
68
+ writeToTarget: ReturnType<typeof createIndexerWriteToTarget>;
69
+ settledRow: ReturnType<typeof createIndexerSettledRow>;
70
+ };
71
+ }, _optional?: Record<string, never>): (row: SearchIndexStateRow, workspaceId: string) => Promise<number>;
72
+ export declare function createIndexerReconcileTarget({ state, maxAttempts, dependencies }: {
64
73
  state: SearchIndexStatePort;
65
74
  maxAttempts: number;
66
- }, dependencies: () => {
67
- resolve: ReturnType<typeof createIndexerResolve>;
68
- settleInFlight: ReturnType<typeof createIndexerSettleInFlight>;
69
- rewriteRow: ReturnType<typeof createIndexerRewriteRow>;
70
- }): (target: SearchTarget, workspaceId: string, limit: number) => Promise<number>;
71
- export declare function createIndexerReconcile({ state }: {
75
+ dependencies: () => {
76
+ resolve: ReturnType<typeof createIndexerResolve>;
77
+ settleInFlight: ReturnType<typeof createIndexerSettleInFlight>;
78
+ rewriteRow: ReturnType<typeof createIndexerRewriteRow>;
79
+ };
80
+ }, _optional?: Record<string, never>): (target: SearchTarget, workspaceId: string, limit: number) => Promise<number>;
81
+ export declare function createIndexerReconcile({ state, dependencies }: {
72
82
  state: SearchIndexStatePort;
73
- }, dependencies: () => {
74
- currentTargets: ReturnType<typeof createIndexerCurrentTargets>;
75
- reconcileTarget: ReturnType<typeof createIndexerReconcileTarget>;
76
- dropRetired: ReturnType<typeof createIndexerDropRetired>;
77
- }): SearchIndexer['reconcile'];
83
+ dependencies: () => {
84
+ currentTargets: ReturnType<typeof createIndexerCurrentTargets>;
85
+ reconcileTarget: ReturnType<typeof createIndexerReconcileTarget>;
86
+ dropRetired: ReturnType<typeof createIndexerDropRetired>;
87
+ };
88
+ }, _optional?: Record<string, never>): SearchIndexer['reconcile'];
78
89
  //# sourceMappingURL=indexer-reconcile.d.ts.map
@@ -19,12 +19,18 @@ export function createIndexerSettledRow({ now }) {
19
19
  * only lands while the row still holds this revision AND this task: an event that wrote a newer
20
20
  * revision while the task was awaited keeps its own pending task (and its retry) intact.
21
21
  */
22
- export function createIndexerSettleTask(dependencies) {
22
+ export function createIndexerSettleTask({ dependencies }, _optional = {}) {
23
23
  return async (row, resolved, { taskId, awaitTask }) => {
24
24
  const { settleObserved, settledRow } = dependencies();
25
- const result = await guarded(() => awaitTask.call(resolved.provider, resolved.ctx, { taskId }));
26
- if (result.status !== 'ok' || result.value === 'pending')
25
+ const result = await guarded({ call: () => awaitTask.call(resolved.provider, resolved.ctx, { taskId }) });
26
+ if (result.status !== 'ok')
27
+ return 0;
28
+ if (result.value === 'pending') {
29
+ // Re-stamp the still-running row (same task, compare-and-swapped) so it moves behind the rest of
30
+ // the oldest-first queue: a long task must not fill every bounded pass and starve finished ones.
31
+ await settleObserved(row, { ...settledRow(row, { status: 'pending', ...(row.lastError === undefined ? {} : { lastError: row.lastError }) }), taskId });
27
32
  return 0;
33
+ }
28
34
  const succeeded = result.value === 'succeeded';
29
35
  const written = await settleObserved(row, settledRow(row, succeeded ? { status: 'indexed' } : { status: 'failed', lastError: 'task_failed' }));
30
36
  return succeeded && written ? 1 : 0;
@@ -35,12 +41,12 @@ export function createIndexerSettleTask(dependencies) {
35
41
  * marked indexed; anything else is returned for a re-load and re-write (never blindly marked
36
42
  * failed: an `unknown` outcome may well have happened).
37
43
  */
38
- export function createIndexerCheckRevisions(dependencies) {
44
+ export function createIndexerCheckRevisions({ dependencies }, _optional = {}) {
39
45
  return async (rows, resolved) => {
40
46
  const { checkChunk } = dependencies();
41
47
  let settled = 0;
42
48
  const rewrite = [];
43
- for (const chunk of chunks(rows, Math.max(1, resolved.provider.capabilities.maxBatch))) {
49
+ for (const chunk of chunks({ items: rows, size: Math.max(1, resolved.provider.capabilities.maxBatch) })) {
44
50
  const checked = await checkChunk(chunk, resolved);
45
51
  settled += checked.settled;
46
52
  rewrite.push(...checked.rewrite);
@@ -49,10 +55,10 @@ export function createIndexerCheckRevisions(dependencies) {
49
55
  };
50
56
  }
51
57
  /** One `revisionOf` call's worth of {@link checkRevisions}; an indeterminate answer leaves the rows as they are. */
52
- export function createIndexerCheckChunk(dependencies) {
58
+ export function createIndexerCheckChunk({ dependencies }, _optional = {}) {
53
59
  return async (chunk, resolved) => {
54
60
  const { settleObserved, settledRow } = dependencies();
55
- const result = await guarded(() => resolved.provider.revisionOf(resolved.ctx, { keys: chunk.map(row => row.key) }));
61
+ const result = await guarded({ call: () => resolved.provider.revisionOf(resolved.ctx, { keys: chunk.map(row => row.key) }) });
56
62
  if (result.status !== 'ok')
57
63
  return { settled: 0, rewrite: [] };
58
64
  const held = new Map(result.value.map(entry => [encodeSearchKey({ key: entry.key }), entry]));
@@ -71,7 +77,7 @@ export function createIndexerCheckChunk(dependencies) {
71
77
  }
72
78
  /** `pending` rows with a task are awaited; `unknown` rows (and a `pending` row whose process died
73
79
  * between marking and the call, so it has no task) are checked with `revisionOf`. */
74
- export function createIndexerSettleInFlight(dependencies) {
80
+ export function createIndexerSettleInFlight({ dependencies }, _optional = {}) {
75
81
  return async (rows, resolved) => {
76
82
  const { settleTask, checkRevisions } = dependencies();
77
83
  const { awaitTask } = resolved.provider;
@@ -88,7 +94,7 @@ export function createIndexerSettleInFlight(dependencies) {
88
94
  };
89
95
  }
90
96
  /** Re-load the row's document from its source and write the current truth again (a retry). */
91
- export function createIndexerRewriteRow({ sources, now }, dependencies) {
97
+ export function createIndexerRewriteRow({ sources, now, dependencies }, _optional = {}) {
92
98
  return async (row, workspaceId) => {
93
99
  const { settleObserved, writeToTarget, settledRow } = dependencies();
94
100
  const source = sources.find(candidate => candidate.collection === row.key.collection);
@@ -100,7 +106,7 @@ export function createIndexerRewriteRow({ sources, now }, dependencies) {
100
106
  return (await writeToTarget({ target: row.target, workspaceId, records: [record], retry: true })).indexed;
101
107
  };
102
108
  }
103
- export function createIndexerReconcileTarget({ state, maxAttempts }, dependencies) {
109
+ export function createIndexerReconcileTarget({ state, maxAttempts, dependencies }, _optional = {}) {
104
110
  return async (target, workspaceId, limit) => {
105
111
  const { resolve, settleInFlight, rewriteRow } = dependencies();
106
112
  // Exhausted failures are excluded before the limit, or the oldest of them would fill every sweep.
@@ -116,7 +122,7 @@ export function createIndexerReconcileTarget({ state, maxAttempts }, dependencie
116
122
  return settled;
117
123
  };
118
124
  }
119
- export function createIndexerReconcile({ state }, dependencies) {
125
+ export function createIndexerReconcile({ state, dependencies }, _optional = {}) {
120
126
  const operation = async ({ siteId, workspaceId }, { limit = 50 } = {}) => {
121
127
  const { currentTargets, reconcileTarget, dropRetired } = dependencies();
122
128
  // Retries the index drop of every replaced generation not yet confirmed gone.
@@ -23,8 +23,13 @@ interface WriteTally {
23
23
  readonly indexed: number;
24
24
  }
25
25
  /** Run one provider call; a provider that throws despite the contract becomes an `unknown`. */
26
- export declare function guarded<T>(call: () => Promise<ProviderResult<T>>): Promise<ProviderResult<T>>;
27
- export declare function chunks<T>(items: readonly T[], size: number): T[][];
26
+ export declare function guarded<T>({ call }: {
27
+ call: () => Promise<ProviderResult<T>>;
28
+ }, _optional?: Record<string, never>): Promise<ProviderResult<T>>;
29
+ export declare function chunks<T>({ items, size }: {
30
+ items: readonly T[];
31
+ size: number;
32
+ }, _optional?: Record<string, never>): T[][];
28
33
  export declare function createIndexerResolve({ required, registry }: {
29
34
  required: SearchIndexerRequired;
30
35
  registry: SearchIndexerRequired['registry'];
@@ -32,11 +37,12 @@ export declare function createIndexerResolve({ required, registry }: {
32
37
  export declare function createIndexerPlanRow({ now }: {
33
38
  now: SearchIndexerRequired['now'];
34
39
  }): (target: SearchTarget, plan: Plan, settle: Settle) => SearchIndexStateRow;
35
- export declare function createIndexerPutPlan({ state }: {
40
+ export declare function createIndexerPutPlan({ state, dependencies }: {
36
41
  state: SearchIndexStatePort;
37
- }, dependencies: () => {
38
- planRow: ReturnType<typeof createIndexerPlanRow>;
39
- }): (target: SearchTarget, plan: Plan, settle: Settle) => Promise<boolean>;
42
+ dependencies: () => {
43
+ planRow: ReturnType<typeof createIndexerPlanRow>;
44
+ };
45
+ }, _optional?: Record<string, never>): (target: SearchTarget, plan: Plan, settle: Settle) => Promise<boolean>;
40
46
  /**
41
47
  * Records worth writing, each with its attempt number. An event/backfill write is skipped when
42
48
  * the row already holds an equal or newer revision (a delayed or duplicated event); a retry only
@@ -53,14 +59,17 @@ export declare function createIndexerFreshRecords({ state }: {
53
59
  * is a compare-and-swap on the `pending` mark this write made (its revision, no task): a newer
54
60
  * revision written meanwhile owns the row and is never overwritten by this older completion.
55
61
  */
56
- export declare function createIndexerSettleCall({ state }: {
62
+ export declare function createIndexerSettleCall({ state, dependencies }: {
57
63
  state: SearchIndexStatePort;
58
- }, dependencies: () => {
59
- planRow: ReturnType<typeof createIndexerPlanRow>;
60
- }): (target: SearchTarget, plans: readonly Plan[], result: ProviderResult<SearchWriteResult>) => Promise<number>;
61
- export declare function createIndexerWriteChunks(dependencies: () => {
62
- settleCall: ReturnType<typeof createIndexerSettleCall>;
63
- }): <T>(input: {
64
+ dependencies: () => {
65
+ planRow: ReturnType<typeof createIndexerPlanRow>;
66
+ };
67
+ }, _optional?: Record<string, never>): (target: SearchTarget, plans: readonly Plan[], result: ProviderResult<SearchWriteResult>) => Promise<number>;
68
+ export declare function createIndexerWriteChunks({ dependencies }: {
69
+ dependencies: () => {
70
+ settleCall: ReturnType<typeof createIndexerSettleCall>;
71
+ };
72
+ }, _optional?: Record<string, never>): <T>(input: {
64
73
  target: SearchTarget;
65
74
  plans: readonly Plan[];
66
75
  maxBatch: number;
@@ -68,12 +77,14 @@ export declare function createIndexerWriteChunks(dependencies: () => {
68
77
  call: (items: T[]) => Promise<ProviderResult<SearchWriteResult>>;
69
78
  }) => Promise<number>;
70
79
  /** Write records to ONE target: mark pending, call the provider in batches, settle each row. */
71
- export declare function createIndexerWriteToTarget(dependencies: () => {
72
- resolve: ReturnType<typeof createIndexerResolve>;
73
- putPlan: ReturnType<typeof createIndexerPutPlan>;
74
- freshRecords: ReturnType<typeof createIndexerFreshRecords>;
75
- writeChunks: ReturnType<typeof createIndexerWriteChunks>;
76
- }): (input: {
80
+ export declare function createIndexerWriteToTarget({ dependencies }: {
81
+ dependencies: () => {
82
+ resolve: ReturnType<typeof createIndexerResolve>;
83
+ putPlan: ReturnType<typeof createIndexerPutPlan>;
84
+ freshRecords: ReturnType<typeof createIndexerFreshRecords>;
85
+ writeChunks: ReturnType<typeof createIndexerWriteChunks>;
86
+ };
87
+ }, _optional?: Record<string, never>): (input: {
77
88
  target: SearchTarget;
78
89
  workspaceId: string;
79
90
  records: readonly SearchSourceRecord[];
@@ -11,7 +11,7 @@ const OUTCOME_STATUS = {
11
11
  rejected: 'failed',
12
12
  };
13
13
  /** Run one provider call; a provider that throws despite the contract becomes an `unknown`. */
14
- export async function guarded(call) {
14
+ export async function guarded({ call }, _optional = {}) {
15
15
  try {
16
16
  return await call();
17
17
  }
@@ -19,7 +19,7 @@ export async function guarded(call) {
19
19
  return providerUnknown({ code: 'unexpected_response', message: 'search provider threw' });
20
20
  }
21
21
  }
22
- export function chunks(items, size) {
22
+ export function chunks({ items, size }, _optional = {}) {
23
23
  const out = [];
24
24
  for (let i = 0; i < items.length; i += size)
25
25
  out.push(items.slice(i, i + size));
@@ -56,7 +56,7 @@ export function createIndexerPlanRow({ now }) {
56
56
  ...(settle.lastError === undefined ? {} : { lastError: settle.lastError }),
57
57
  });
58
58
  }
59
- export function createIndexerPutPlan({ state }, dependencies) {
59
+ export function createIndexerPutPlan({ state, dependencies }, _optional = {}) {
60
60
  return (target, plan, settle) => {
61
61
  const { planRow } = dependencies();
62
62
  return state.put({ row: planRow(target, plan, settle) });
@@ -86,7 +86,7 @@ export function createIndexerFreshRecords({ state }) {
86
86
  * is a compare-and-swap on the `pending` mark this write made (its revision, no task): a newer
87
87
  * revision written meanwhile owns the row and is never overwritten by this older completion.
88
88
  */
89
- export function createIndexerSettleCall({ state }, dependencies) {
89
+ export function createIndexerSettleCall({ state, dependencies }, _optional = {}) {
90
90
  return async (target, plans, result) => {
91
91
  const { planRow } = dependencies();
92
92
  let indexed = 0;
@@ -99,19 +99,19 @@ export function createIndexerSettleCall({ state }, dependencies) {
99
99
  return indexed;
100
100
  };
101
101
  }
102
- export function createIndexerWriteChunks(dependencies) {
102
+ export function createIndexerWriteChunks({ dependencies }, _optional = {}) {
103
103
  return async (input) => {
104
104
  const { settleCall } = dependencies();
105
105
  let indexed = 0;
106
- for (const chunk of chunks(input.plans, input.maxBatch)) {
107
- const result = await guarded(() => input.call(chunk.map(input.payload)));
106
+ for (const chunk of chunks({ items: input.plans, size: input.maxBatch })) {
107
+ const result = await guarded({ call: () => input.call(chunk.map(input.payload)) });
108
108
  indexed += await settleCall(input.target, chunk, result);
109
109
  }
110
110
  return indexed;
111
111
  };
112
112
  }
113
113
  /** Write records to ONE target: mark pending, call the provider in batches, settle each row. */
114
- export function createIndexerWriteToTarget(dependencies) {
114
+ export function createIndexerWriteToTarget({ dependencies }, _optional = {}) {
115
115
  return async (input) => {
116
116
  const { resolve, putPlan, freshRecords, writeChunks } = dependencies();
117
117
  const { target } = input;
package/dist/indexer.js CHANGED
@@ -32,30 +32,30 @@ export function createSearchIndexer(required, optional = {}) {
32
32
  const { maxAttempts = 5, scanPageSize = 100 } = optional;
33
33
  const resolve = createIndexerResolve({ required, registry });
34
34
  const planRow = createIndexerPlanRow({ now });
35
- const putPlan = createIndexerPutPlan({ state }, () => ({ planRow }));
35
+ const putPlan = createIndexerPutPlan({ state, dependencies: () => ({ planRow }) });
36
36
  const settleObserved = createIndexerSettleObserved({ state });
37
37
  const freshRecords = createIndexerFreshRecords({ state });
38
- const settleCall = createIndexerSettleCall({ state }, () => ({ planRow }));
39
- const writeChunks = createIndexerWriteChunks(() => ({ settleCall }));
40
- const writeToTarget = createIndexerWriteToTarget(() => ({ resolve, putPlan, freshRecords, writeChunks }));
38
+ const settleCall = createIndexerSettleCall({ state, dependencies: () => ({ planRow }) });
39
+ const writeChunks = createIndexerWriteChunks({ dependencies: () => ({ settleCall }) });
40
+ const writeToTarget = createIndexerWriteToTarget({ dependencies: () => ({ resolve, putPlan, freshRecords, writeChunks }) });
41
41
  const currentTargets = createIndexerCurrentTargets({ targets });
42
42
  const settledRow = createIndexerSettledRow({ now });
43
- const settleTask = createIndexerSettleTask(() => ({ settleObserved, settledRow }));
44
- const checkRevisions = createIndexerCheckRevisions(() => ({ checkChunk }));
45
- const checkChunk = createIndexerCheckChunk(() => ({ settleObserved, settledRow }));
46
- const settleInFlight = createIndexerSettleInFlight(() => ({ settleTask, checkRevisions }));
47
- const rewriteRow = createIndexerRewriteRow({ sources, now }, () => ({ settleObserved, writeToTarget, settledRow }));
48
- const reconcileTarget = createIndexerReconcileTarget({ state, maxAttempts }, () => ({ resolve, settleInFlight, rewriteRow }));
49
- const scanSource = createIndexerScanSource({ state, scanPageSize }, () => ({ writeToTarget }));
50
- const promote = createIndexerPromote({ targets, state }, () => ({ dropRetired }));
51
- const dropRetired = createIndexerDropRetired({ targets, state }, () => ({ resolve }));
52
- const backfillTarget = createIndexerBackfillTarget({ sources }, () => ({ scanSource }));
43
+ const settleTask = createIndexerSettleTask({ dependencies: () => ({ settleObserved, settledRow }) });
44
+ const checkRevisions = createIndexerCheckRevisions({ dependencies: () => ({ checkChunk }) });
45
+ const checkChunk = createIndexerCheckChunk({ dependencies: () => ({ settleObserved, settledRow }) });
46
+ const settleInFlight = createIndexerSettleInFlight({ dependencies: () => ({ settleTask, checkRevisions }) });
47
+ const rewriteRow = createIndexerRewriteRow({ sources, now, dependencies: () => ({ settleObserved, writeToTarget, settledRow }) });
48
+ const reconcileTarget = createIndexerReconcileTarget({ state, maxAttempts, dependencies: () => ({ resolve, settleInFlight, rewriteRow }) });
49
+ const scanSource = createIndexerScanSource({ state, scanPageSize, dependencies: () => ({ writeToTarget }) });
50
+ const promote = createIndexerPromote({ targets, state, dependencies: () => ({ dropRetired }) });
51
+ const dropRetired = createIndexerDropRetired({ targets, state, dependencies: () => ({ resolve }) });
52
+ const backfillTarget = createIndexerBackfillTarget({ sources, dependencies: () => ({ scanSource }) });
53
53
  const readMarks = createIndexerReadMarks({ sources, state });
54
54
  return {
55
55
  eventNames: [...new Set(sources.flatMap(source => source.events))],
56
56
  handleEvent: createIndexerHandleEvent({ required, sources }, () => ({ writeToTarget, currentTargets })),
57
- reconcile: createIndexerReconcile({ state }, () => ({ currentTargets, reconcileTarget, dropRetired })),
58
- backfill: createIndexerBackfill({ targets }, () => ({ resolve, promote, backfillTarget, readMarks })),
57
+ reconcile: createIndexerReconcile({ state, dependencies: () => ({ currentTargets, reconcileTarget, dropRetired }) }),
58
+ backfill: createIndexerBackfill({ targets, dependencies: () => ({ resolve, promote, backfillTarget, readMarks }) }),
59
59
  startRebuild: createIndexerStartRebuild({ targets }),
60
60
  };
61
61
  }
@@ -0,0 +1,65 @@
1
+ import { type JsonRouteSpec } from '@jini-ai/core/contracts/server';
2
+ import type { SearchServiceResult } from '@jini-ai/core/contracts/site/search';
3
+ import { parseSearchRequest } from '../../../http-query.js';
4
+ /**
5
+ * @file `GET /api/search?q=&collection=&limit=&cursor=` — the public site-search endpoint (lot S4).
6
+ * Public and unauthenticated, like the other site routes; every hit has already been re-checked by
7
+ * the search service's fail-closed access port before it reaches this file.
8
+ *
9
+ * Viewer audiences come ONLY from the visitor's own member session cookie (the same cookie and
10
+ * resolver the member-gated page routes use), never from the query string: a member sees their
11
+ * members-only matches, everyone else public ones. Because the answer can differ per visitor, it is
12
+ * sent `private, no-store`, the convention every member-gated route here follows.
13
+ *
14
+ * Responses: `200 { hits: [{ url, title, snippet, highlights, collection }], nextCursor }` (plain-text
15
+ * snippets; `nextCursor` is `null` on the last page), `400 { error: 'invalid_request', message }`,
16
+ * `503 { error: 'search_unavailable', reason }` (no runtime in this composition, no configured
17
+ * provider, timeout, provider down, access check failed) and `500` for anything unexpected.
18
+ *
19
+ * The session token is read from that cookie by the host, bound to the request (`sessionToken`); the
20
+ * `500` is the host's error port, since a rejection is thrown, not caught here.
21
+ */
22
+ /** The query shape `parseSearchRequest` accepts (what the service is asked for, minus audiences). */
23
+ type ParsedSearchQuery = Extract<ReturnType<typeof parseSearchRequest>, {
24
+ query: unknown;
25
+ }>['query'];
26
+ /** The site-search runtime the route reads: the service, the site it serves and the session audiences. */
27
+ export interface SiteSearchRouteRuntime {
28
+ readonly siteId: string;
29
+ readonly workspaceId: string;
30
+ /** Settles once plugin providers were offered to the registry. */
31
+ readonly ready: Promise<unknown>;
32
+ readonly service: {
33
+ query(required: {
34
+ siteId: string;
35
+ workspaceId: string;
36
+ query: ParsedSearchQuery;
37
+ }, optional: {
38
+ audiences: readonly string[];
39
+ }): Promise<SearchServiceResult>;
40
+ };
41
+ audiencesForSession(required: {
42
+ readonly sessionToken?: string;
43
+ }): Promise<readonly string[]>;
44
+ }
45
+ /** The narrow deps this route needs. Absent `siteSearch` = this composition has no search. */
46
+ export interface SiteSearchRouteDeps {
47
+ readonly siteSearch?: SiteSearchRouteRuntime | undefined;
48
+ readonly clock?: {
49
+ nowMs(): number;
50
+ } | undefined;
51
+ /** The host's query limits: longest `q` (UTF-16 code units), collections, page size and cursor length. */
52
+ readonly limits: Parameters<typeof parseSearchRequest>[0]['limits'];
53
+ /** Bound to the request by the host: the visitor's own member session token, if any. */
54
+ readonly sessionToken: () => string | undefined;
55
+ /** Bound to the request by the host: records the successful search as a visitor event (consent is the host's). */
56
+ readonly recordSearchPerformed: (required: {
57
+ readonly properties: Readonly<Record<string, string>>;
58
+ }) => void;
59
+ }
60
+ /** `GET /api/search`; mount it with request-bound `sessionToken` / `recordSearchPerformed` deps. */
61
+ export declare const siteSearchRoute: JsonRouteSpec<Readonly<Record<string, unknown>>, unknown, SiteSearchRouteDeps> & {
62
+ readonly responseHeaders: Readonly<Record<string, string>>;
63
+ };
64
+ export {};
65
+ //# sourceMappingURL=search.d.ts.map