@docslurp/contrib-search-compat 0.0.0-stage → 0.4.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 DocSlurp, Inc. and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 DocSlurp, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ DocSlurp
2
+ Copyright 2025-2026 DocSlurp, Inc. and contributors
3
+
4
+ Earlier versions were distributed under the Apache License, Version 2.0.
5
+ Existing license grants remain in effect for those versions. Retain applicable
6
+ upstream copyright, patent, license and attribution notices when redistributing
7
+ code from those versions. The accompanying Apache-2.0 text preserves the
8
+ previous repository notice and supplies the future license for SSPL versions.
9
+
10
+ Third-party components retain their own licenses. DocSlurp's license does not
11
+ relicense dependencies, models, fonts, assets or separately licensed files.
12
+ See THIRD_PARTY_NOTICES.md in the repository for the compatibility review.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # @docslurp/contrib-search-compat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Package docs](https://docslurp.io/docs/packages/contrib-search-compat) · [GitHub](https://github.com/DocSlurp/docslurp-oss/tree/main/packages/contrib-search-compat) · [npm](https://www.npmjs.com/package/@docslurp/contrib-search-compat)
4
+
5
+ Keep your existing search calls and get DocSlurp results with citations. One package, one subpath per client:
6
+
7
+ | Subpath | Replaces | Entry point |
8
+ | --- | --- | --- |
9
+ | `@docslurp/contrib-search-compat/algolia` | Algolia (Lite-style and `initIndex()`) | `docslurpAlgoliaClient()` |
10
+ | `@docslurp/contrib-search-compat/meilisearch` | Meilisearch | `createDocSlurpMeilisearchClient()` |
11
+ | `@docslurp/contrib-search-compat/typesense` | Typesense | `createDocSlurpTypesenseClient()` |
12
+ | `@docslurp/contrib-search-compat/pagefind` | Pagefind | `createDocSlurpPagefind()` |
13
+
14
+ Requires `@docslurp/sdk` 0.4.0 or newer. The Meilisearch, Typesense and Pagefind subpaths are the same adapters you can import from `@docslurp/sdk/search-adapters`. In the browser, pass a browser key as `clientKey`. Workspace references (`indexName`, `index(...)`, `collections(...)`, `workspace`) accept a workspace ID, slug or `default`; the `workspace` option also accepts a name.
15
+
16
+ Renamed from `@docslurp/compat-algolia`, `@docslurp/compat-meilisearch`, `@docslurp/compat-typesense` and `@docslurp/compat-pagefind`; see [`docs/releases.md`](https://github.com/DocSlurp/docslurp-oss/blob/main/docs/releases.md) for the migration.
17
+
18
+ ## Algolia
19
+
20
+ Move Algolia search code to DocSlurp without rewriting your calls. This client keeps the current Lite-style methods (`searchSingleIndex`, `search`, `searchForFacetValues`) and the legacy `initIndex()` surface, plus settings, synonym and rule sync, click and conversion events, and imports. Results come from DocSlurp retrieval and keep their citations.
21
+
22
+ ### Search from the browser
23
+
24
+ ```ts
25
+ import { docslurpAlgoliaClient } from "@docslurp/contrib-search-compat/algolia";
26
+
27
+ const client = docslurpAlgoliaClient({
28
+ apiUrl: process.env.PUBLIC_DOCSLURP_API_URL!,
29
+ clientKey: process.env.PUBLIC_DOCSLURP_CLIENT_KEY!, // A browser key: search-only, limited to your allowed websites.
30
+ glossary: { ml: ["machine learning"] } // Optional synonyms, expanded locally before each query.
31
+ });
32
+
33
+ // indexName is a workspace slug, UUID or "default".
34
+ const res = await client.searchSingleIndex({
35
+ indexName: "product-manuals",
36
+ searchParams: { query: "ml models", hitsPerPage: 10 }
37
+ });
38
+ console.log(res.hits);
39
+
40
+ const facets = await client.searchForFacetValues({
41
+ indexName: "product-manuals",
42
+ facetName: "filename",
43
+ searchForFacetValuesRequest: { facetQuery: "invoice" }
44
+ });
45
+ console.log(facets.facetHits);
46
+
47
+ // Report a click on a result.
48
+ await client.clickedObjectIDsAfterSearch({ indexName: "product-manuals", queryID: res.queryID, objectIDs: ["doc-1:0"] });
49
+ ```
50
+
51
+ ### Sync settings, synonyms and rules from your server
52
+
53
+ Reads such as `getSettings` work with a browser key. Writes (`setSettings`, `saveSynonyms`, `saveRules`, `importIndex`) need a server key with the `workspaces:manage` scope, which only organization owners and admins can grant, and the key owner must be able to edit the workspace. Run them from a backend job or migration script, never in the browser:
54
+
55
+ ```ts
56
+ const admin = docslurpAlgoliaClient({
57
+ apiUrl: "https://docslurp.io",
58
+ clientKey: process.env.DOCSLURP_API_KEY!, // A server key with the workspaces:manage scope. The option is named clientKey.
59
+ });
60
+
61
+ const settings = await admin.getSettings({ indexName: "product-manuals" });
62
+ await admin.saveSynonyms({ indexName: "product-manuals", synonymHit: [{ type: "synonym", synonyms: ["invoice", "bill"] }] });
63
+ await admin.saveRules({ indexName: "product-manuals", rules: [{ objectID: "rule-1", condition: { pattern: "invoice" } }] });
64
+ ```
65
+
66
+ [`@docslurp/contrib-algolia-server`](https://docslurp.io/docs/packages/contrib-algolia-server) wraps these writes with server-side helper names.
67
+
68
+ ### Supported call shapes
69
+
70
+ - Legacy `index.search("query", { hitsPerPage: 10 })` and `index.search({ query: "query", hitsPerPage: 10 })` both work.
71
+ - InstantSearch-style `client.search([{ indexName, params: { query } }])` is converted to the API's flat request shape. The current `{ requests }` form works too, with up to 10 requests.
72
+ - The client follows common Algolia request and response shapes, but ranking comes from DocSlurp retrieval, not Algolia's ranking.
73
+ - `filters` and `facetFilters` support `tags`, `mime_type`, `filename` (exact, case-sensitive match), `filenameContains` (case-insensitive literal substring), `language`, `heading`, `documentId` and `runId` clauses joined with `AND`. `OR` works only between values of one `tags` or `mime_type` attribute, for example `(tags:a OR tags:b)` or `facetFilters: [["tags:a", "tags:b"]]`, because DocSlurp matches any of the listed values; each attribute may appear in one `AND` clause. `numericFilters` (and numeric clauses in `filters`) support `page` with `=`, `<`, `<=`, `>`, `>=` and `page:1 TO 5`.
74
+ - Any parameter that narrows results and is outside that subset is rejected, never ignored, so a filter you rely on for scoping cannot silently stop applying. That covers other attributes, `NOT` and `-` negation, `!=`, mixed `AND`/`OR` without parentheses, nested groups, malformed syntax, non-empty `tagFilters`, geo parameters, `restrictSearchableAttributes`, `ruleContexts`, `distinct`, `offset`/`length`, `advancedSyntax`, the URL-encoded `params` string and any unknown or misspelled key (such as `facetfilters`). Limits: `filters` up to 8 KB, 100 clauses in total, 1 KB per clause, 255 characters per filename value, 100 entries per `facetFilters`/`numericFilters` array, arrays nested at most two levels deep and a 1 MB request body.
75
+ - Ranking, presentation and analytics parameters that never change which hits match are accepted with any value and ignored: `analytics`, `analyticsTags`, `clickAnalytics`, `getRankingInfo`, `userToken`, `enablePersonalization`, `personalizationImpact`, `enableABTest`, `enableReRanking`, `percentileComputation`, `attributesToHighlight`, `attributesToSnippet`, `snippetEllipsisText`, `restrictHighlightAndSnippetArrays`, `responseFields`, `maxValuesPerFacet`, `sortFacetValuesBy`, `facetingAfterDistinct`, `optionalFilters`, `sumOrFiltersScores` and `aroundPrecision`. `type` is accepted as `"default"` on every route.
76
+ - Query-matching parameters change how many hits match, and DocSlurp does not apply them, so they are accepted only with Algolia's default or a more permissive value: `typoTolerance: true`, `allowTyposOnNumericTokens: true`, `decompoundQuery: true`, `minWordSizefor1Typo` up to 4, `minWordSizefor2Typos` up to 8, and any boolean or language list for `ignorePlurals`, `removeStopWords`, `queryLanguages` and `naturalLanguages`. Restrictive values, such as `typoTolerance: false`, `"min"` or `"strict"`, and a non-empty `keepDiacriticsOnCharacters`, are rejected. Empty or disabled defaults such as `tagFilters: ""` and `aroundLatLngViaIP: false` are accepted, so standard InstantSearch requests work.
77
+ - Rejections are HTTP 400 with `code: "UNSUPPORTED_SEARCH_OPTION"` and a message naming the clause or parameter, returned before any retrieval runs; in a batched `search()` one bad request rejects the whole batch. The client throws a `SearchCompatibilityError` (exported from this subpath) for these responses, and also for legacy `{ indexName, params }` entries whose `params` is not a plain object.
78
+ - Facet counts and `searchForFacetValues` cover `filename` only, counted within the retrieved results. Highlight tags return the passage text without match markup.
79
+ - `searchSingleIndex` with an empty `query` returns HTTP 400; batched requests with an empty query or an unknown index name return zero hits.
80
+
81
+ ## Meilisearch
82
+
83
+ `createDocSlurpMeilisearchClient()` supports `index(workspace).search(q, params)`.
84
+
85
+ ```ts
86
+ import { createDocSlurpMeilisearchClient } from "@docslurp/contrib-search-compat/meilisearch";
87
+ ```
88
+
89
+ ## Typesense
90
+
91
+ `createDocSlurpTypesenseClient()` supports `collections(workspace).documents().search(params)` and `multiSearch.perform()` (up to 10 searches).
92
+
93
+ ```ts
94
+ import { createDocSlurpTypesenseClient } from "@docslurp/contrib-search-compat/typesense";
95
+ ```
96
+
97
+ ## Pagefind
98
+
99
+ `createDocSlurpPagefind()` supports `search(term)` with lazy `data()` results. It requires `workspace` and a `resolveUrl` function that maps each citation to a public page URL.
100
+
101
+ ```ts
102
+ import { createDocSlurpPagefind } from "@docslurp/contrib-search-compat/pagefind";
103
+ ```
104
+
105
+ See the [search integrations guide](https://docslurp.io/docs/search-integrations) for contract limits, source routing, CMS and platform setup, and agent handoffs.
@@ -0,0 +1,190 @@
1
+ import { SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
2
+ export { SearchCompatibilityError };
3
+ export type AlgoliaSearchRequest = {
4
+ query: string;
5
+ page?: number;
6
+ hitsPerPage?: number;
7
+ filters?: string;
8
+ facetFilters?: string[] | string[][];
9
+ numericFilters?: string[] | string[][];
10
+ facets?: string[];
11
+ attributesToRetrieve?: string[];
12
+ highlightPreTag?: string;
13
+ highlightPostTag?: string;
14
+ };
15
+ export type AlgoliaMultipleQueriesRequest = {
16
+ requests: Array<AlgoliaSearchRequest & {
17
+ indexName: string;
18
+ }>;
19
+ };
20
+ export type AlgoliaLegacyQueries = Array<{
21
+ indexName: string;
22
+ params: AlgoliaSearchRequest;
23
+ }>;
24
+ export type AlgoliaSearchSingleIndexRequest = {
25
+ indexName: string;
26
+ searchParams: AlgoliaSearchRequest;
27
+ };
28
+ export type AlgoliaSearchForFacetValuesRequest = {
29
+ indexName: string;
30
+ facetName: string;
31
+ searchForFacetValuesRequest: {
32
+ facetQuery: string;
33
+ query?: string;
34
+ filters?: string;
35
+ facetFilters?: string[] | string[][];
36
+ numericFilters?: string[] | string[][];
37
+ maxFacetHits?: number;
38
+ };
39
+ };
40
+ export type AlgoliaHit = Record<string, unknown> & {
41
+ objectID: string;
42
+ };
43
+ export type AlgoliaSearchResponse = {
44
+ hits: AlgoliaHit[];
45
+ page: number;
46
+ nbHits: number;
47
+ nbPages: number;
48
+ hitsPerPage: number;
49
+ processingTimeMS: number;
50
+ query: string;
51
+ queryID?: string;
52
+ params: string;
53
+ facets?: Record<string, Record<string, number>>;
54
+ exhaustiveNbHits?: boolean;
55
+ };
56
+ export type AlgoliaCompatSettings = Record<string, unknown>;
57
+ export type AlgoliaSynonymEntry = {
58
+ objectID?: string;
59
+ type?: "synonym" | "oneWaySynonym";
60
+ synonyms?: string[];
61
+ input?: string;
62
+ };
63
+ export type AlgoliaRuleEntry = Record<string, unknown>;
64
+ export type AlgoliaFacetHit = {
65
+ value: string;
66
+ highlighted: string;
67
+ count: number;
68
+ };
69
+ export interface DocSlurpAlgoliaClientOptions {
70
+ apiUrl: string;
71
+ clientKey: string;
72
+ glossary?: Record<string, string[]>;
73
+ fetch?: typeof globalThis.fetch;
74
+ }
75
+ export declare function docslurpAlgoliaClient(opts: DocSlurpAlgoliaClientOptions): {
76
+ initIndex: (indexName: string) => {
77
+ search: (query: string | AlgoliaSearchRequest, params?: Omit<AlgoliaSearchRequest, "query">) => Promise<AlgoliaSearchResponse>;
78
+ getSettings: () => Promise<AlgoliaCompatSettings>;
79
+ setSettings: (settings: AlgoliaCompatSettings) => Promise<{
80
+ ok: boolean;
81
+ settings: AlgoliaCompatSettings;
82
+ }>;
83
+ searchSynonyms: () => Promise<{
84
+ hits: AlgoliaSynonymEntry[];
85
+ }>;
86
+ saveSynonyms: (synonyms: AlgoliaSynonymEntry[]) => Promise<{
87
+ updatedAt: string;
88
+ count: number;
89
+ }>;
90
+ searchRules: () => Promise<{
91
+ hits: AlgoliaRuleEntry[];
92
+ }>;
93
+ saveRules: (rules: AlgoliaRuleEntry[]) => Promise<{
94
+ updatedAt: string;
95
+ count: number;
96
+ }>;
97
+ searchForFacetValues: (facetName: string, requestBody: Omit<AlgoliaSearchForFacetValuesRequest["searchForFacetValuesRequest"], "facetName">) => Promise<{
98
+ facetHits: AlgoliaFacetHit[];
99
+ exhaustiveFacetsCount: boolean;
100
+ }>;
101
+ getAnalytics: () => Promise<{
102
+ queries: number;
103
+ zeroResults: number;
104
+ clicks: number;
105
+ conversions: number;
106
+ }>;
107
+ clickedObjectIDsAfterSearch: (payload: {
108
+ queryID?: string;
109
+ objectIDs: string[];
110
+ positions?: number[];
111
+ }) => Promise<{
112
+ status: string;
113
+ }>;
114
+ convertedObjectIDsAfterSearch: (payload: {
115
+ queryID?: string;
116
+ objectIDs: string[];
117
+ eventName?: string;
118
+ }) => Promise<{
119
+ status: string;
120
+ }>;
121
+ };
122
+ searchSingleIndex: (requestBody: AlgoliaSearchSingleIndexRequest) => Promise<AlgoliaSearchResponse>;
123
+ searchForFacetValues: (requestBody: AlgoliaSearchForFacetValuesRequest) => Promise<{
124
+ facetHits: AlgoliaFacetHit[];
125
+ exhaustiveFacetsCount: boolean;
126
+ }>;
127
+ getSettings: (requestBody: {
128
+ indexName: string;
129
+ }) => Promise<AlgoliaCompatSettings>;
130
+ setSettings: (requestBody: {
131
+ indexName: string;
132
+ indexSettings: AlgoliaCompatSettings;
133
+ }) => Promise<{
134
+ ok: boolean;
135
+ settings: AlgoliaCompatSettings;
136
+ }>;
137
+ searchSynonyms: (requestBody: {
138
+ indexName: string;
139
+ }) => Promise<{
140
+ hits: AlgoliaSynonymEntry[];
141
+ }>;
142
+ saveSynonyms: (requestBody: {
143
+ indexName: string;
144
+ synonymHit: AlgoliaSynonymEntry[];
145
+ }) => Promise<{
146
+ updatedAt: string;
147
+ count: number;
148
+ }>;
149
+ searchRules: (requestBody: {
150
+ indexName: string;
151
+ }) => Promise<{
152
+ hits: AlgoliaRuleEntry[];
153
+ }>;
154
+ saveRules: (requestBody: {
155
+ indexName: string;
156
+ rules: AlgoliaRuleEntry[];
157
+ }) => Promise<{
158
+ updatedAt: string;
159
+ count: number;
160
+ }>;
161
+ getAnalytics: (requestBody: {
162
+ indexName: string;
163
+ }) => Promise<{
164
+ queries: number;
165
+ zeroResults: number;
166
+ clicks: number;
167
+ conversions: number;
168
+ }>;
169
+ clickedObjectIDsAfterSearch: (requestBody: {
170
+ indexName: string;
171
+ queryID?: string;
172
+ objectIDs: string[];
173
+ positions?: number[];
174
+ }) => Promise<{
175
+ status: string;
176
+ }>;
177
+ convertedObjectIDsAfterSearch: (requestBody: {
178
+ indexName: string;
179
+ queryID?: string;
180
+ objectIDs: string[];
181
+ eventName?: string;
182
+ }) => Promise<{
183
+ status: string;
184
+ }>;
185
+ search: (requestBody: AlgoliaMultipleQueriesRequest | AlgoliaLegacyQueries) => Promise<{
186
+ results: AlgoliaSearchResponse[];
187
+ }>;
188
+ importIndex: (payload: Record<string, unknown>) => Promise<unknown>;
189
+ };
190
+ export default docslurpAlgoliaClient;
@@ -0,0 +1,220 @@
1
+ import { SearchCompatibilityError, unsupportedSearchOptionMessage } from "@docslurp/sdk/search-adapters";
2
+ export { SearchCompatibilityError };
3
+ function expandQuery(query, glossary) {
4
+ if (!glossary || Object.keys(glossary).length === 0)
5
+ return query;
6
+ const norm = {};
7
+ for (const [k, v] of Object.entries(glossary))
8
+ norm[k.toLowerCase()] = v;
9
+ const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);
10
+ const out = [];
11
+ let i = 0;
12
+ const alt = (t) => `(${[t, ...(norm[t] ?? [])].join(" OR ")})`;
13
+ while (i < tokens.length) {
14
+ if (i + 2 < tokens.length) {
15
+ const tri = `${tokens[i]} ${tokens[i + 1]} ${tokens[i + 2]}`;
16
+ if (norm[tri]) {
17
+ out.push(alt(tri));
18
+ i += 3;
19
+ continue;
20
+ }
21
+ }
22
+ if (i + 1 < tokens.length) {
23
+ const bi = `${tokens[i]} ${tokens[i + 1]}`;
24
+ if (norm[bi]) {
25
+ out.push(alt(bi));
26
+ i += 2;
27
+ continue;
28
+ }
29
+ }
30
+ out.push(norm[tokens[i]] ? alt(tokens[i]) : tokens[i]);
31
+ i++;
32
+ }
33
+ return out.join(" ");
34
+ }
35
+ /**
36
+ * Legacy `{ indexName, params }` entries must carry a plain object. Spreading a
37
+ * URL-encoded params string or a URLSearchParams would drop its filters silently.
38
+ */
39
+ function plainParams(params) {
40
+ if (params === undefined)
41
+ return {};
42
+ const prototype = params !== null && typeof params === "object" ? Object.getPrototypeOf(params) : undefined;
43
+ if (prototype !== Object.prototype && prototype !== null) {
44
+ throw new SearchCompatibilityError("Algolia request params must be a plain object; URL-encoded params strings are not supported.");
45
+ }
46
+ return params;
47
+ }
48
+ export function docslurpAlgoliaClient(opts) {
49
+ const { apiUrl, clientKey, glossary } = opts;
50
+ // Server keys (dslp_priv_…) must never ship to a browser; client keys are dslp_pub_….
51
+ if (typeof window !== "undefined" && typeof document !== "undefined" && clientKey.startsWith("dslp_priv_")) {
52
+ throw new Error("DocSlurp server keys (dslp_priv_…) must never be used in browser code. Use a search-only, domain-restricted client key (dslp_pub_…).");
53
+ }
54
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
55
+ const base = apiUrl.replace(/\/$/, "");
56
+ if (!fetchImpl) {
57
+ throw new Error("A fetch implementation is required.");
58
+ }
59
+ async function request(pathname, init) {
60
+ const res = await fetchImpl(`${base}${pathname}`, {
61
+ ...init,
62
+ headers: {
63
+ ...(init?.body ? { "Content-Type": "application/json" } : {}),
64
+ ...(init?.headers ?? {}),
65
+ Authorization: `Bearer ${clientKey}`
66
+ }
67
+ });
68
+ if (!res.ok) {
69
+ const text = await res.text();
70
+ // Unsupported filters and options are rejected with HTTP 400 rather than ignored.
71
+ const unsupported = unsupportedSearchOptionMessage(res.status, text);
72
+ if (unsupported)
73
+ throw new SearchCompatibilityError(unsupported);
74
+ throw new Error(`DocSlurp Algolia-compat request failed: ${res.status} ${text}`);
75
+ }
76
+ return await res.json();
77
+ }
78
+ async function searchSingleIndex(requestBody) {
79
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/query`, {
80
+ method: "POST",
81
+ body: JSON.stringify({
82
+ ...requestBody.searchParams,
83
+ query: expandQuery(requestBody.searchParams.query, glossary)
84
+ })
85
+ });
86
+ }
87
+ async function searchForFacetValues(requestBody) {
88
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/facets/${encodeURIComponent(requestBody.facetName)}/query`, {
89
+ method: "POST",
90
+ body: JSON.stringify(requestBody.searchForFacetValuesRequest)
91
+ });
92
+ }
93
+ async function getSettings(requestBody) {
94
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/settings`);
95
+ }
96
+ async function setSettings(requestBody) {
97
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/settings`, {
98
+ method: "PUT",
99
+ body: JSON.stringify(requestBody.indexSettings)
100
+ });
101
+ }
102
+ async function searchSynonyms(requestBody) {
103
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/synonyms`);
104
+ }
105
+ async function saveSynonyms(requestBody) {
106
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/synonyms/batch`, {
107
+ method: "POST",
108
+ body: JSON.stringify({ synonyms: requestBody.synonymHit })
109
+ });
110
+ }
111
+ async function searchRules(requestBody) {
112
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/rules`);
113
+ }
114
+ async function saveRules(requestBody) {
115
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/rules/batch`, {
116
+ method: "POST",
117
+ body: JSON.stringify({ rules: requestBody.rules })
118
+ });
119
+ }
120
+ async function getAnalytics(requestBody) {
121
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/analytics/summary`);
122
+ }
123
+ async function clickedObjectIDsAfterSearch(requestBody) {
124
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/analytics/click`, {
125
+ method: "POST",
126
+ body: JSON.stringify({
127
+ queryID: requestBody.queryID,
128
+ objectIDs: requestBody.objectIDs,
129
+ positions: requestBody.positions
130
+ })
131
+ });
132
+ }
133
+ async function convertedObjectIDsAfterSearch(requestBody) {
134
+ return await request(`/compat/algolia/1/indexes/${encodeURIComponent(requestBody.indexName)}/analytics/conversion`, {
135
+ method: "POST",
136
+ body: JSON.stringify({
137
+ queryID: requestBody.queryID,
138
+ objectIDs: requestBody.objectIDs,
139
+ eventName: requestBody.eventName
140
+ })
141
+ });
142
+ }
143
+ function initIndex(indexName) {
144
+ return {
145
+ search: async (query, params = {}) => {
146
+ return await searchSingleIndex({
147
+ indexName,
148
+ searchParams: typeof query === "string" ? { ...params, query } : query
149
+ });
150
+ },
151
+ getSettings: async () => {
152
+ return await getSettings({ indexName });
153
+ },
154
+ setSettings: async (settings) => {
155
+ return await setSettings({ indexName, indexSettings: settings });
156
+ },
157
+ searchSynonyms: async () => {
158
+ return await searchSynonyms({ indexName });
159
+ },
160
+ saveSynonyms: async (synonyms) => {
161
+ return await saveSynonyms({ indexName, synonymHit: synonyms });
162
+ },
163
+ searchRules: async () => {
164
+ return await searchRules({ indexName });
165
+ },
166
+ saveRules: async (rules) => {
167
+ return await saveRules({ indexName, rules });
168
+ },
169
+ searchForFacetValues: async (facetName, requestBody) => {
170
+ return await searchForFacetValues({
171
+ indexName,
172
+ facetName,
173
+ searchForFacetValuesRequest: requestBody
174
+ });
175
+ },
176
+ getAnalytics: async () => {
177
+ return await getAnalytics({ indexName });
178
+ },
179
+ clickedObjectIDsAfterSearch: async (payload) => {
180
+ return await clickedObjectIDsAfterSearch({ indexName, ...payload });
181
+ },
182
+ convertedObjectIDsAfterSearch: async (payload) => {
183
+ return await convertedObjectIDsAfterSearch({ indexName, ...payload });
184
+ }
185
+ };
186
+ }
187
+ return {
188
+ initIndex,
189
+ searchSingleIndex,
190
+ searchForFacetValues,
191
+ getSettings,
192
+ setSettings,
193
+ searchSynonyms,
194
+ saveSynonyms,
195
+ searchRules,
196
+ saveRules,
197
+ getAnalytics,
198
+ clickedObjectIDsAfterSearch,
199
+ convertedObjectIDsAfterSearch,
200
+ search: async (requestBody) => {
201
+ const requests = Array.isArray(requestBody) ? requestBody.map(({ indexName, params }) => ({ indexName, ...plainParams(params) })) : requestBody.requests;
202
+ return await request(`/compat/algolia/1/indexes/*/queries`, {
203
+ method: "POST",
204
+ body: JSON.stringify({
205
+ requests: requests.map((entry) => ({
206
+ ...entry,
207
+ query: expandQuery(entry.query, glossary)
208
+ }))
209
+ })
210
+ });
211
+ },
212
+ importIndex: async (payload) => {
213
+ return await request(`/compat/algolia/1/import`, {
214
+ method: "POST",
215
+ body: JSON.stringify(payload)
216
+ });
217
+ }
218
+ };
219
+ }
220
+ export default docslurpAlgoliaClient;
@@ -0,0 +1,2 @@
1
+ export { createDocSlurpMeilisearchClient, createDocSlurpMeilisearchClient as default, SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
2
+ export type { SearchAdapterOptions } from "@docslurp/sdk/search-adapters";
@@ -0,0 +1 @@
1
+ export { createDocSlurpMeilisearchClient, createDocSlurpMeilisearchClient as default, SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
@@ -0,0 +1,2 @@
1
+ export { createDocSlurpPagefind, createDocSlurpPagefind as default, SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
2
+ export type { SearchAdapterOptions } from "@docslurp/sdk/search-adapters";
@@ -0,0 +1 @@
1
+ export { createDocSlurpPagefind, createDocSlurpPagefind as default, SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
@@ -0,0 +1,2 @@
1
+ export { createDocSlurpTypesenseClient, createDocSlurpTypesenseClient as default, SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
2
+ export type { SearchAdapterOptions } from "@docslurp/sdk/search-adapters";
@@ -0,0 +1 @@
1
+ export { createDocSlurpTypesenseClient, createDocSlurpTypesenseClient as default, SearchCompatibilityError } from "@docslurp/sdk/search-adapters";
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@docslurp/contrib-search-compat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.4.0",
4
+ "description": "Drop-in Algolia, Meilisearch, Typesense and Pagefind search clients backed by DocSlurp retrieval, one package with a subpath per client.",
5
+ "license": "MIT",
6
+ "homepage": "https://docslurp.io/docs/packages/contrib-search-compat",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DocSlurp/docslurp-oss.git",
10
+ "directory": "packages/contrib-search-compat"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/DocSlurp/docslurp-oss/issues"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ "./algolia": {
18
+ "types": "./dist/algolia.d.ts",
19
+ "import": "./dist/algolia.js"
20
+ },
21
+ "./meilisearch": {
22
+ "types": "./dist/meilisearch.d.ts",
23
+ "import": "./dist/meilisearch.js"
24
+ },
25
+ "./typesense": {
26
+ "types": "./dist/typesense.d.ts",
27
+ "import": "./dist/typesense.js"
28
+ },
29
+ "./pagefind": {
30
+ "types": "./dist/pagefind.d.ts",
31
+ "import": "./dist/pagefind.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE",
38
+ "NOTICE",
39
+ "LICENSES"
40
+ ],
41
+ "dependencies": {
42
+ "@docslurp/sdk": "^0.4.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^26.6.6",
46
+ "typescript": "^7.0.2",
47
+ "typescript-compiler-api": "npm:typescript@6.0.3"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc -p tsconfig.json",
54
+ "typecheck": "tsc -p tsconfig.json --noEmit",
55
+ "test": "pnpm build && node ../../scripts/node-test.mjs test/*.test.mjs"
56
+ }
6
57
  }