@embedpdf/plugin-search 3.0.0-next.16 → 3.0.0-next.18

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/dist/index.cjs CHANGED
@@ -15,7 +15,7 @@ const NO_PROGRESS = Object.freeze({
15
15
  pagesSearched: 0,
16
16
  pageCount: 0
17
17
  });
18
- const initialSearchState = () => ({
18
+ const initialSearchModel = () => ({
19
19
  query: null,
20
20
  status: "idle",
21
21
  operationId: null,
@@ -27,7 +27,7 @@ const initialSearchState = () => ({
27
27
  });
28
28
  /** A new scan starts: everything from the previous session is dropped. */
29
29
  const startSession = (_state, query, operationId) => ({
30
- ...initialSearchState(),
30
+ ...initialSearchModel(),
31
31
  query,
32
32
  status: "searching",
33
33
  operationId
@@ -75,7 +75,7 @@ const setActiveHit = (state, index) => state.activeHitIndex === index ? state :
75
75
  ...state,
76
76
  activeHitIndex: index
77
77
  };
78
- const clearSession = (state) => state.status === "idle" ? state : initialSearchState();
78
+ const clearSession = (state) => state.status === "idle" ? state : initialSearchModel();
79
79
  /**
80
80
  * Where `hit` is in `hits`: the same object, or else the hit that covers the
81
81
  * same characters of the same page, so a hit kept from before the search ran
@@ -364,7 +364,7 @@ const searchPlugin = (config) => (0, _embedpdf_core.definePlugin)({
364
364
  token: require_contract.SearchToken,
365
365
  scope: "document",
366
366
  optional: [_embedpdf_plugin_stage_contract.StageToken],
367
- state: initialSearchState,
367
+ state: initialSearchModel,
368
368
  settings: {
369
369
  defaults: require_contract.SEARCH_DEFAULTS,
370
370
  registered: config
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["StageToken","PluginError","SearchToken","StageToken","SEARCH_DEFAULTS","SearchToken"],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchState {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchState = (): SearchState => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchState,\n query: SearchQuery,\n operationId: string,\n): SearchState => ({ ...initialSearchState(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchState,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchState {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchState): SearchState => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchState): SearchState => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchState, error: PluginErrorInfo): SearchState => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchState, index: number): SearchState =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchState): SearchState =>\n state.status === 'idle' ? state : initialSearchState();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchState,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchState,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchState, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: permission fallback (snippets → none\n * when they are denied, unless pinned), restart-once on a stale cursor,\n * projection per slice. Returns true on exhaustion, false when the signal\n * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n let snippets = options.snippets ?? true;\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied (no doc.text.copy)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the anchor —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n anchor: arrival.anchor,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return Promise.resolve({ status: 'complete', hitCount: 0 });\n return search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchState } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchState,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState } from '@embedpdf/core';\n\nimport { SearchToken } from './contract';\nimport { NO_PROGRESS } from './model';\n\nexport const searchState = defineState(SearchToken, {\n read: (search) => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CAAC;CACP,YAAY,CAAC;CACb,gBAAgB;CAChB,UAAU;CACV,OAAO;AACT;;AAGA,MAAa,gBACX,QACA,OACA,iBACiB;CAAE,GAAG,mBAAmB;CAAG;CAAO,QAAQ;CAAa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YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["StageToken","PluginError","SearchToken","StageToken","SEARCH_DEFAULTS","SearchToken"],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchModel {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchModel = (): SearchModel => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchModel,\n query: SearchQuery,\n operationId: string,\n): SearchModel => ({ ...initialSearchModel(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchModel,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchModel {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchModel, error: PluginErrorInfo): SearchModel => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchModel, index: number): SearchModel =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchModel): SearchModel =>\n state.status === 'idle' ? state : initialSearchModel();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchModel,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchModel,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchModel, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: permission fallback (snippets → none\n * when they are denied, unless pinned), restart-once on a stale cursor,\n * projection per slice. Returns true on exhaustion, false when the signal\n * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n let snippets = options.snippets ?? true;\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied (no doc.text.copy)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the anchor —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n anchor: arrival.anchor,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return Promise.resolve({ status: 'complete', hitCount: 0 });\n return search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchModel } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchModel,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport { SearchToken, type SearchHit, type SearchProgress, type SearchStatus } from './contract';\nimport { NO_PROGRESS } from './model';\n\n/** The query, where the search is, how many hits it found, the active hit, and why it failed. */\nexport interface SearchState {\n /** What is searched for, or `null` before a search. */\n readonly query: SearchQuery | null;\n /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */\n readonly status: SearchStatus;\n /** How many hits were found so far. */\n readonly hitCount: number;\n /** The active hit's index, or `-1` when no hit is active. */\n readonly activeHitIndex: number;\n /** The active hit, or `null`. */\n readonly activeHit: SearchHit | null;\n /** How many pages the search went through, of how many. */\n readonly progress: SearchProgress;\n /** Why the search failed, or `null`. */\n readonly error: PluginErrorInfo | null;\n}\n\nexport const searchState = defineState(SearchToken, {\n read: (search): SearchState => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CAAC;CACP,YAAY,CAAC;CACb,gBAAgB;CAChB,UAAU;CACV,OAAO;AACT;;AAGA,MAAa,gBACX,QACA,OACA,iBACiB;CAAE,GAAG,mBAAmB;CAAG;CAAO,QAAQ;CAAa;AAAY;AAEtF,MAAM,gBAAgB,MAAsB,UAC1C,KAAK,kBAAkB,MAAM,iBAAiB,KAAK,cAAc,MAAM;;;;;;;AAQzE,SAAgB,WACd,OACA,MACA,OACa;CACb,MAAM,WAAW,aAAa,MAAM,UAAU,KAAK,IAAI,MAAM,WAAW;CACxE,IAAI,KAAK,WAAW,GAAG,OAAO,aAAa,MAAM,WAAW,QAAQ;EAAE,GAAG;EAAO;CAAS;CACzF,MAAM,aAAmD,EAAE,GAAG,MAAM,WAAW;CAC/E,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,mBA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,QAAQ;EACnB,mBAAmB,gBAAgB;EACnC,aAAa,UAAU;EACvB,aAAa,UAAU;EACvB,UAAU,OAAO;EACjB,oBAAoB,iBAAiB;EACrC,WAAW,QAAQ;CACrB;CAEA,OAAO;EACL;EACA,UAAU;GAGR,IAAI,cAAmC;GACvC,IAAI,OAAO,IAAI,IAAI,cAAc;IAC/B,IAAI,MAAM,CAAC,CAAC,WAAW,QAAQ;IAC/B,cAAc;IACd,cAAc,IAAI,MAAM,MAAM,sBAAsB;KAClD,cAAc;KACd,IAAS,QAAQ,CAAC,CAAC,YAAY,CAE/B,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF;AACF;;;;;;;;;ACxWA,MAAa,gBAAgB,YAAA,GAAA,eAAA,aAAA,CACd;CACX,IAAI;CACJ,OAAOC,iBAAAA;CACP,OAAO;CACP,UAAU,CAACC,gCAAAA,UAAU;CACrB,OAAO;CACP,UAAU;EAAE,UAAUC,iBAAAA;EAAiB,YAAY;CAAO;CAC1D,QAAQ;AACV,CAAC;;;;;;;;;ACQH,MAAa,eAAA,GAAA,eAAA,YAAA,CAA0BC,iBAAAA,aAAa;CAClD,OAAO,YAAyB;EAC9B,OAAO,OAAO,SAAS;EACvB,QAAQ,OAAO,UAAU;EACzB,UAAU,OAAO,YAAY;EAC7B,gBAAgB,OAAO,kBAAkB;EACzC,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
package/dist/index.d.cts CHANGED
@@ -2,7 +2,7 @@ import { A as SearchToken, C as SearchSettings, D as TextSegment, E as SearchSta
2
2
  import { PageRef, PluginErrorInfo } from "@embedpdf/core";
3
3
  import { SearchQuery as SearchQuery$1 } from "@embedpdf/engine-core/runtime";
4
4
  //#region src/model.d.ts
5
- interface SearchState {
5
+ interface SearchModel {
6
6
  /** The query being searched, as the engine matches it. Null when idle. */
7
7
  readonly query: SearchQuery$1 | null;
8
8
  readonly status: SearchStatus;
@@ -24,18 +24,27 @@ interface SearchState {
24
24
  * scans start at the current page and navigation reveals hits. `config` is
25
25
  * the settings the app registers, over {@link SEARCH_DEFAULTS}.
26
26
  */
27
- declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").PluginDef<SearchState, SearchCapability, SearchSettings>;
27
+ declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").PluginDef<SearchModel, SearchCapability, SearchSettings>;
28
28
  //#endregion
29
29
  //#region src/state.d.ts
30
- declare const searchState: import("@embedpdf/core").StateDeclaration<SearchCapability, {
31
- query: import("@embedpdf/engine-core/runtime").SearchQuery | null;
32
- status: SearchStatus;
33
- hitCount: number;
34
- activeHitIndex: number;
35
- activeHit: SearchHit | null;
36
- progress: SearchProgress;
37
- error: import("@embedpdf/core").PluginErrorInfo | null;
38
- }>;
30
+ /** The query, where the search is, how many hits it found, the active hit, and why it failed. */
31
+ interface SearchState {
32
+ /** What is searched for, or `null` before a search. */
33
+ readonly query: SearchQuery$1 | null;
34
+ /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */
35
+ readonly status: SearchStatus;
36
+ /** How many hits were found so far. */
37
+ readonly hitCount: number;
38
+ /** The active hit's index, or `-1` when no hit is active. */
39
+ readonly activeHitIndex: number;
40
+ /** The active hit, or `null`. */
41
+ readonly activeHit: SearchHit | null;
42
+ /** How many pages the search went through, of how many. */
43
+ readonly progress: SearchProgress;
44
+ /** Why the search failed, or `null`. */
45
+ readonly error: PluginErrorInfo | null;
46
+ }
47
+ declare const searchState: import("@embedpdf/core").StateDeclaration<SearchCapability, SearchState>;
39
48
  //#endregion
40
- export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchBlendMode, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, SearchStatus, SearchToken, TextSegment, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
49
+ export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchBlendMode, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, type SearchState, SearchStatus, SearchToken, TextSegment, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
41
50
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { A as SearchToken, C as SearchSettings, D as TextSegment, E as SearchSta
2
2
  import { PageRef, PluginErrorInfo } from "@embedpdf/core";
3
3
  import { SearchQuery as SearchQuery$1 } from "@embedpdf/engine-core/runtime";
4
4
  //#region src/model.d.ts
5
- interface SearchState {
5
+ interface SearchModel {
6
6
  /** The query being searched, as the engine matches it. Null when idle. */
7
7
  readonly query: SearchQuery$1 | null;
8
8
  readonly status: SearchStatus;
@@ -24,18 +24,27 @@ interface SearchState {
24
24
  * scans start at the current page and navigation reveals hits. `config` is
25
25
  * the settings the app registers, over {@link SEARCH_DEFAULTS}.
26
26
  */
27
- declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").PluginDef<SearchState, SearchCapability, SearchSettings>;
27
+ declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").PluginDef<SearchModel, SearchCapability, SearchSettings>;
28
28
  //#endregion
29
29
  //#region src/state.d.ts
30
- declare const searchState: import("@embedpdf/core").StateDeclaration<SearchCapability, {
31
- query: import("@embedpdf/engine-core/runtime").SearchQuery | null;
32
- status: SearchStatus;
33
- hitCount: number;
34
- activeHitIndex: number;
35
- activeHit: SearchHit | null;
36
- progress: SearchProgress;
37
- error: import("@embedpdf/core").PluginErrorInfo | null;
38
- }>;
30
+ /** The query, where the search is, how many hits it found, the active hit, and why it failed. */
31
+ interface SearchState {
32
+ /** What is searched for, or `null` before a search. */
33
+ readonly query: SearchQuery$1 | null;
34
+ /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */
35
+ readonly status: SearchStatus;
36
+ /** How many hits were found so far. */
37
+ readonly hitCount: number;
38
+ /** The active hit's index, or `-1` when no hit is active. */
39
+ readonly activeHitIndex: number;
40
+ /** The active hit, or `null`. */
41
+ readonly activeHit: SearchHit | null;
42
+ /** How many pages the search went through, of how many. */
43
+ readonly progress: SearchProgress;
44
+ /** Why the search failed, or `null`. */
45
+ readonly error: PluginErrorInfo | null;
46
+ }
47
+ declare const searchState: import("@embedpdf/core").StateDeclaration<SearchCapability, SearchState>;
39
48
  //#endregion
40
- export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchBlendMode, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, SearchStatus, SearchToken, TextSegment, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
49
+ export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchBlendMode, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, type SearchState, SearchStatus, SearchToken, TextSegment, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
41
50
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ const NO_PROGRESS = Object.freeze({
13
13
  pagesSearched: 0,
14
14
  pageCount: 0
15
15
  });
16
- const initialSearchState = () => ({
16
+ const initialSearchModel = () => ({
17
17
  query: null,
18
18
  status: "idle",
19
19
  operationId: null,
@@ -25,7 +25,7 @@ const initialSearchState = () => ({
25
25
  });
26
26
  /** A new scan starts: everything from the previous session is dropped. */
27
27
  const startSession = (_state, query, operationId) => ({
28
- ...initialSearchState(),
28
+ ...initialSearchModel(),
29
29
  query,
30
30
  status: "searching",
31
31
  operationId
@@ -73,7 +73,7 @@ const setActiveHit = (state, index) => state.activeHitIndex === index ? state :
73
73
  ...state,
74
74
  activeHitIndex: index
75
75
  };
76
- const clearSession = (state) => state.status === "idle" ? state : initialSearchState();
76
+ const clearSession = (state) => state.status === "idle" ? state : initialSearchModel();
77
77
  /**
78
78
  * Where `hit` is in `hits`: the same object, or else the hit that covers the
79
79
  * same characters of the same page, so a hit kept from before the search ran
@@ -362,7 +362,7 @@ const searchPlugin = (config) => definePlugin({
362
362
  token: SearchToken,
363
363
  scope: "document",
364
364
  optional: [StageToken],
365
- state: initialSearchState,
365
+ state: initialSearchModel,
366
366
  settings: {
367
367
  defaults: SEARCH_DEFAULTS,
368
368
  registered: config
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchState {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchState = (): SearchState => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchState,\n query: SearchQuery,\n operationId: string,\n): SearchState => ({ ...initialSearchState(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchState,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchState {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchState): SearchState => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchState): SearchState => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchState, error: PluginErrorInfo): SearchState => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchState, index: number): SearchState =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchState): SearchState =>\n state.status === 'idle' ? state : initialSearchState();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchState,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchState,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchState, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: permission fallback (snippets → none\n * when they are denied, unless pinned), restart-once on a stale cursor,\n * projection per slice. Returns true on exhaustion, false when the signal\n * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n let snippets = options.snippets ?? true;\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied (no doc.text.copy)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the anchor —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n anchor: arrival.anchor,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return Promise.resolve({ status: 'complete', hitCount: 0 });\n return search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchState } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchState,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState } from '@embedpdf/core';\n\nimport { SearchToken } from './contract';\nimport { NO_PROGRESS } from './model';\n\nexport const searchState = defineState(SearchToken, {\n read: (search) => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CAAC;CACP,YAAY,CAAC;CACb,gBAAgB;CAChB,UAAU;CACV,OAAO;AACT;;AAGA,MAAa,gBACX,QACA,OACA,iBACiB;CAAE,GAAG,mBAAmB;CAAG;CAAO,QAAQ;CAAa;AAAY;AAEtF,MAAM,gBAAgB,MAA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e;KACb,IAAI,SAAS;IACf;IACA,UAAU,SAAS,IAAI,KAAK,GAAG,IAAI;GACrC,CACF,GACe,MAAM,IAAI,YAAY,uBAAuB,UAAU,iBAAiB;GACvF,OAAO;EACT;EAEA,WAAW,QAAQ;EACnB,mBAAmB,gBAAgB;EACnC,aAAa,UAAU;EACvB,aAAa,UAAU;EACvB,UAAU,OAAO;EACjB,oBAAoB,iBAAiB;EACrC,WAAW,QAAQ;CACrB;CAEA,OAAO;EACL;EACA,UAAU;GAGR,IAAI,cAAmC;GACvC,IAAI,OAAO,IAAI,IAAI,cAAc;IAC/B,IAAI,MAAM,CAAC,CAAC,WAAW,QAAQ;IAC/B,cAAc;IACd,cAAc,IAAI,MAAM,MAAM,sBAAsB;KAClD,cAAc;KACd,IAAS,QAAQ,CAAC,CAAC,YAAY,CAE/B,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF;AACF;;;;;;;;;ACxWA,MAAa,gBAAgB,WAC3B,aAAa;CACX,IAAI;CACJ,OAAO;CACP,OAAO;CACP,UAAU,CAAC,UAAU;CACrB,OAAO;CACP,UAAU;EAAE,UAAU;EAAiB,YAAY;CAAO;CAC1D,QAAQ;AACV,CAAC;;;;;;;;;ACXH,MAAa,cAAc,YAAY,aAAa;CAClD,OAAO,YAAY;EACjB,OAAO,OAAO,SAAS;EACvB,QAAQ,OAAO,UAAU;EACzB,UAAU,OAAO,YAAY;EAC7B,gBAAgB,OAAO,kBAAkB;EACzC,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchModel {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchModel = (): SearchModel => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchModel,\n query: SearchQuery,\n operationId: string,\n): SearchModel => ({ ...initialSearchModel(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchModel,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchModel {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchModel, error: PluginErrorInfo): SearchModel => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchModel, index: number): SearchModel =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchModel): SearchModel =>\n state.status === 'idle' ? state : initialSearchModel();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchModel,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchModel,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchModel, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: permission fallback (snippets → none\n * when they are denied, unless pinned), restart-once on a stale cursor,\n * projection per slice. Returns true on exhaustion, false when the signal\n * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n let snippets = options.snippets ?? true;\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied (no doc.text.copy)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the anchor —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n anchor: arrival.anchor,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return Promise.resolve({ status: 'complete', hitCount: 0 });\n return search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchModel } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchModel,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport { SearchToken, type SearchHit, type SearchProgress, type SearchStatus } from './contract';\nimport { NO_PROGRESS } from './model';\n\n/** The query, where the search is, how many hits it found, the active hit, and why it failed. */\nexport interface SearchState {\n /** What is searched for, or `null` before a search. */\n readonly query: SearchQuery | null;\n /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */\n readonly status: SearchStatus;\n /** How many hits were found so far. */\n readonly hitCount: number;\n /** The active hit's index, or `-1` when no hit is active. */\n readonly activeHitIndex: number;\n /** The active hit, or `null`. */\n readonly activeHit: SearchHit | null;\n /** How many pages the search went through, of how many. */\n readonly progress: SearchProgress;\n /** Why the search failed, or `null`. */\n readonly error: PluginErrorInfo | null;\n}\n\nexport const searchState = defineState(SearchToken, {\n read: (search): SearchState => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CAAC;CACP,YAAY,CAAC;CACb,gBAAgB;CAChB,UAAU;CACV,OAAO;AACT;;AAGA,MAAa,gBACX,QACA,OACA,iBACiB;CAAE,GAAG,mBAAmB;CAAG;CAAO,QAAQ;CAAa;AAAY;AAEtF,MAAM,gBAAgB,MAAsB,UAC1C,KAAK,kBAAkB,MAAM,iBAAiB,KAAK,cAAc,MAAM;;;;;;;AAQzE,SAAgB,WACd,OACA,MACA,OACa;CACb,MAAM,WAAW,aAAa,MAAM,UAAU,KAAK,IAAI,MAAM,WAAW;CACxE,IAAI,KAAK,WAAW,GAAG,OAAO,aAAa,MAAM,WAAW,QAAQ;EAAE,GAAG;EAAO;CAAS;CACzF,MAAM,aAAmD,EAAE,GAAG,MAAM,WAAW;CAC/E,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,mBAAmB,IAAI,KAAK;EAClC,WAAW,oBAAoB,CAAC,GAAI,WAAW,qBAAqB,CAAC,GAAI,GAAG;CAC9E;CACA,OAAO;EACL,GAAG;EACH,MAAM,CAAC,GAAG,MAAM,MAAM,GAAG,IAAI;EAC7B;EACA,gBAAgB,MAAM,mBAAmB,KAAK,IAAI,MAAM;EACxD;CACF;AACF;AAEA,MAAa,mBAAmB,WAAqC;CACnE,GAAG;CACH,QAAQ;AACV;AAEA,MAAa,iBAAiB,WAAqC;CACjE,GAAG;CACH,QAAQ;AACV;AAE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UAAU;EAAE,UAAU;EAAiB,YAAY;CAAO;CAC1D,QAAQ;AACV,CAAC;;;;;;;;;ACQH,MAAa,cAAc,YAAY,aAAa;CAClD,OAAO,YAAyB;EAC9B,OAAO,OAAO,SAAS;EACvB,QAAQ,OAAO,UAAU;EACzB,UAAU,OAAO,YAAY;EAC7B,gBAAgB,OAAO,kBAAkB;EACzC,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embedpdf/plugin-search",
3
- "version": "3.0.0-next.16",
3
+ "version": "3.0.0-next.18",
4
4
  "private": false,
5
5
  "description": "Document text search: drives the engine's budgeted search slices, converts match rects to content space, and integrates with the Stage for viewport-first scanning and reveal-on-navigate.",
6
6
  "type": "module",
@@ -22,10 +22,10 @@
22
22
  "dist"
23
23
  ],
24
24
  "dependencies": {
25
- "@embedpdf/core": "3.0.0-next.16",
26
- "@embedpdf/core-geometry": "3.0.0-next.16",
27
- "@embedpdf/plugin-stage": "3.0.0-next.16",
28
- "@embedpdf/engine-core": "3.0.0-next.16"
25
+ "@embedpdf/core": "3.0.0-next.18",
26
+ "@embedpdf/plugin-stage": "3.0.0-next.18",
27
+ "@embedpdf/core-geometry": "3.0.0-next.18",
28
+ "@embedpdf/engine-core": "3.0.0-next.18"
29
29
  },
30
30
  "devDependencies": {
31
31
  "typescript": "^5.0.0",