@tinacms/search 0.0.0-00f6525-20241015065741

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,184 @@
1
+ Copyright (c) 2023-present Forestry.io Holdings Inc.
2
+
3
+ Portions of the TinaCMS software are licensed as follows:
4
+
5
+ * All software that resides under the "packages/@tinacms/datalayer/" and the "packages/@tinacms/graphql/" directories (the "Tina Data Layer"), is licensed under the license defined in "packages/@tinacms/datalayer/LICENSE".
6
+
7
+ * All software outside of the above-mentioned directories is available under the "Apache 2.0" license as set forth below.
8
+
9
+ Apache License
10
+ Version 2.0, January 2004
11
+ http://www.apache.org/licenses/
12
+
13
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
14
+
15
+ 1. Definitions.
16
+
17
+ "License" shall mean the terms and conditions for use, reproduction,
18
+ and distribution as defined by Sections 1 through 9 of this document.
19
+
20
+ "Licensor" shall mean the copyright owner or entity authorized by
21
+ the copyright owner that is granting the License.
22
+
23
+ "Legal Entity" shall mean the union of the acting entity and all
24
+ other entities that control, are controlled by, or are under common
25
+ control with that entity. For the purposes of this definition,
26
+ "control" means (i) the power, direct or indirect, to cause the
27
+ direction or management of such entity, whether by contract or
28
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
29
+ outstanding shares, or (iii) beneficial ownership of such entity.
30
+
31
+ "You" (or "Your") shall mean an individual or Legal Entity
32
+ exercising permissions granted by this License.
33
+
34
+ "Source" form shall mean the preferred form for making modifications,
35
+ including but not limited to software source code, documentation
36
+ source, and configuration files.
37
+
38
+ "Object" form shall mean any form resulting from mechanical
39
+ transformation or translation of a Source form, including but
40
+ not limited to compiled object code, generated documentation,
41
+ and conversions to other media types.
42
+
43
+ "Work" shall mean the work of authorship, whether in Source or
44
+ Object form, made available under the License, as indicated by a
45
+ copyright notice that is included in or attached to the work
46
+ (an example is provided in the Appendix below).
47
+
48
+ "Derivative Works" shall mean any work, whether in Source or Object
49
+ form, that is based on (or derived from) the Work and for which the
50
+ editorial revisions, annotations, elaborations, or other modifications
51
+ represent, as a whole, an original work of authorship. For the purposes
52
+ of this License, Derivative Works shall not include works that remain
53
+ separable from, or merely link (or bind by name) to the interfaces of,
54
+ the Work and Derivative Works thereof.
55
+
56
+ "Contribution" shall mean any work of authorship, including
57
+ the original version of the Work and any modifications or additions
58
+ to that Work or Derivative Works thereof, that is intentionally
59
+ submitted to Licensor for inclusion in the Work by the copyright owner
60
+ or by an individual or Legal Entity authorized to submit on behalf of
61
+ the copyright owner. For the purposes of this definition, "submitted"
62
+ means any form of electronic, verbal, or written communication sent
63
+ to the Licensor or its representatives, including but not limited to
64
+ communication on electronic mailing lists, source code control systems,
65
+ and issue tracking systems that are managed by, or on behalf of, the
66
+ Licensor for the purpose of discussing and improving the Work, but
67
+ excluding communication that is conspicuously marked or otherwise
68
+ designated in writing by the copyright owner as "Not a Contribution."
69
+
70
+ "Contributor" shall mean Licensor and any individual or Legal Entity
71
+ on behalf of whom a Contribution has been received by Licensor and
72
+ subsequently incorporated within the Work.
73
+
74
+ 2. Grant of Copyright License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ copyright license to reproduce, prepare Derivative Works of,
78
+ publicly display, publicly perform, sublicense, and distribute the
79
+ Work and such Derivative Works in Source or Object form.
80
+
81
+ 3. Grant of Patent License. Subject to the terms and conditions of
82
+ this License, each Contributor hereby grants to You a perpetual,
83
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
84
+ (except as stated in this section) patent license to make, have made,
85
+ use, offer to sell, sell, import, and otherwise transfer the Work,
86
+ where such license applies only to those patent claims licensable
87
+ by such Contributor that are necessarily infringed by their
88
+ Contribution(s) alone or by combination of their Contribution(s)
89
+ with the Work to which such Contribution(s) was submitted. If You
90
+ institute patent litigation against any entity (including a
91
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
92
+ or a Contribution incorporated within the Work constitutes direct
93
+ or contributory patent infringement, then any patent licenses
94
+ granted to You under this License for that Work shall terminate
95
+ as of the date such litigation is filed.
96
+
97
+ 4. Redistribution. You may reproduce and distribute copies of the
98
+ Work or Derivative Works thereof in any medium, with or without
99
+ modifications, and in Source or Object form, provided that You
100
+ meet the following conditions:
101
+
102
+ (a) You must give any other recipients of the Work or
103
+ Derivative Works a copy of this License; and
104
+
105
+ (b) You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+
108
+ (c) You must retain, in the Source form of any Derivative Works
109
+ that You distribute, all copyright, patent, trademark, and
110
+ attribution notices from the Source form of the Work,
111
+ excluding those notices that do not pertain to any part of
112
+ the Derivative Works; and
113
+
114
+ (d) If the Work includes a "NOTICE" text file as part of its
115
+ distribution, then any Derivative Works that You distribute must
116
+ include a readable copy of the attribution notices contained
117
+ within such NOTICE file, excluding those notices that do not
118
+ pertain to any part of the Derivative Works, in at least one
119
+ of the following places: within a NOTICE text file distributed
120
+ as part of the Derivative Works; within the Source form or
121
+ documentation, if provided along with the Derivative Works; or,
122
+ within a display generated by the Derivative Works, if and
123
+ wherever such third-party notices normally appear. The contents
124
+ of the NOTICE file are for informational purposes only and
125
+ do not modify the License. You may add Your own attribution
126
+ notices within Derivative Works that You distribute, alongside
127
+ or as an addendum to the NOTICE text from the Work, provided
128
+ that such additional attribution notices cannot be construed
129
+ as modifying the License.
130
+
131
+ You may add Your own copyright statement to Your modifications and
132
+ may provide additional or different license terms and conditions
133
+ for use, reproduction, or distribution of Your modifications, or
134
+ for any such Derivative Works as a whole, provided Your use,
135
+ reproduction, and distribution of the Work otherwise complies with
136
+ the conditions stated in this License.
137
+
138
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
139
+ any Contribution intentionally submitted for inclusion in the Work
140
+ by You to the Licensor shall be under the terms and conditions of
141
+ this License, without any additional terms or conditions.
142
+ Notwithstanding the above, nothing herein shall supersede or modify
143
+ the terms of any separate license agreement you may have executed
144
+ with Licensor regarding such Contributions.
145
+
146
+ 6. Trademarks. This License does not grant permission to use the trade
147
+ names, trademarks, service marks, or product names of the Licensor,
148
+ except as required for reasonable and customary use in describing the
149
+ origin of the Work and reproducing the content of the NOTICE file.
150
+
151
+ 7. Disclaimer of Warranty. Unless required by applicable law or
152
+ agreed to in writing, Licensor provides the Work (and each
153
+ Contributor provides its Contributions) on an "AS IS" BASIS,
154
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
155
+ implied, including, without limitation, any warranties or conditions
156
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
157
+ PARTICULAR PURPOSE. You are solely responsible for determining the
158
+ appropriateness of using or redistributing the Work and assume any
159
+ risks associated with Your exercise of permissions under this License.
160
+
161
+ 8. Limitation of Liability. In no event and under no legal theory,
162
+ whether in tort (including negligence), contract, or otherwise,
163
+ unless required by applicable law (such as deliberate and grossly
164
+ negligent acts) or agreed to in writing, shall any Contributor be
165
+ liable to You for damages, including any direct, indirect, special,
166
+ incidental, or consequential damages of any character arising as a
167
+ result of this License or out of the use or inability to use the
168
+ Work (including but not limited to damages for loss of goodwill,
169
+ work stoppage, computer failure or malfunction, or any and all
170
+ other commercial damages or losses), even if such Contributor
171
+ has been advised of the possibility of such damages.
172
+
173
+ 9. Accepting Warranty or Additional Liability. While redistributing
174
+ the Work or Derivative Works thereof, You may choose to offer,
175
+ and charge a fee for, acceptance of support, warranty, indemnity,
176
+ or other liability obligations and/or rights consistent with this
177
+ License. However, in accepting such obligations, You may act only
178
+ on Your own behalf and on Your sole responsibility, not on behalf
179
+ of any other Contributor, and only if You agree to indemnify,
180
+ defend, and hold each Contributor harmless for any liability
181
+ incurred by, or claims asserted against, such Contributor by reason
182
+ of your accepting any such warranty or additional liability.
183
+
184
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
File without changes
@@ -0,0 +1,39 @@
1
+ import type { SearchClient } from '../types';
2
+ import { MemoryLevel } from 'memory-level';
3
+ type TinaSearchIndexerClientOptions = {
4
+ stopwordLanguages?: string[];
5
+ tokenSplitRegex?: string;
6
+ };
7
+ type TinaCloudSearchIndexerClientOptions = {
8
+ apiUrl: string;
9
+ branch: string;
10
+ indexerToken: string;
11
+ } & TinaSearchIndexerClientOptions;
12
+ export declare class LocalSearchIndexClient implements SearchClient {
13
+ searchIndex: any;
14
+ protected readonly memoryLevel: MemoryLevel;
15
+ private readonly stopwords;
16
+ private readonly tokenSplitRegex;
17
+ constructor(options: TinaSearchIndexerClientOptions);
18
+ onStartIndexing(): Promise<void>;
19
+ put(docs: any[]): Promise<any>;
20
+ del(ids: string[]): Promise<any>;
21
+ query(query: string, options: {
22
+ cursor?: string;
23
+ limit?: number;
24
+ } | undefined): Promise<{
25
+ results: any[];
26
+ total: number;
27
+ nextCursor: string | null;
28
+ prevCursor: string | null;
29
+ }>;
30
+ export(filename: string): Promise<void>;
31
+ }
32
+ export declare class TinaCMSSearchIndexClient extends LocalSearchIndexClient {
33
+ private readonly apiUrl;
34
+ private readonly branch;
35
+ private readonly indexerToken;
36
+ constructor(options: TinaCloudSearchIndexerClientOptions);
37
+ onFinishIndexing(): Promise<void>;
38
+ }
39
+ export {};
@@ -0,0 +1,16 @@
1
+ export type { SearchClient } from './types';
2
+ export { processDocumentForIndexing } from './indexer/utils';
3
+ export declare const queryToSearchIndexQuery: (query: string, stopwordLanguages?: string[]) => any;
4
+ export declare const optionsToSearchIndexOptions: (options?: {
5
+ limit?: number;
6
+ cursor?: string;
7
+ }) => {};
8
+ export declare const parseSearchIndexResponse: (data: any, options?: {
9
+ limit?: number;
10
+ cursor?: string;
11
+ }) => {
12
+ results: any;
13
+ total: any;
14
+ prevCursor: any;
15
+ nextCursor: string;
16
+ };
@@ -0,0 +1,215 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("stopword")) : typeof define === "function" && define.amd ? define(["exports", "stopword"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["@tinacms/search"] = {}, global.NOOP));
3
+ })(this, function(exports2, sw) {
4
+ "use strict";
5
+ function _interopNamespaceDefault(e) {
6
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
7
+ if (e) {
8
+ for (const k in e) {
9
+ if (k !== "default") {
10
+ const d = Object.getOwnPropertyDescriptor(e, k);
11
+ Object.defineProperty(n, k, d.get ? d : {
12
+ enumerable: true,
13
+ get: () => e[k]
14
+ });
15
+ }
16
+ }
17
+ }
18
+ n.default = e;
19
+ return Object.freeze(n);
20
+ }
21
+ const sw__namespace = /* @__PURE__ */ _interopNamespaceDefault(sw);
22
+ class StringBuilder {
23
+ constructor(limit) {
24
+ this.length = 0;
25
+ this.buffer = [];
26
+ this.limit = limit;
27
+ }
28
+ append(str) {
29
+ if (this.length + str.length > this.limit) {
30
+ return true;
31
+ } else {
32
+ this.buffer.push(str);
33
+ this.length += str.length;
34
+ if (this.length > this.limit) {
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+ }
40
+ toString() {
41
+ return this.buffer.join(" ");
42
+ }
43
+ }
44
+ const extractText = (data, acc, indexableNodeTypes) => {
45
+ var _a, _b;
46
+ if (data) {
47
+ if (indexableNodeTypes.indexOf(data.type) !== -1 && (data.text || data.value)) {
48
+ const tokens = tokenizeString(data.text || data.value);
49
+ for (const token of tokens) {
50
+ if (acc.append(token)) {
51
+ return;
52
+ }
53
+ }
54
+ }
55
+ (_b = (_a = data.children) == null ? void 0 : _a.forEach) == null ? void 0 : _b.call(
56
+ _a,
57
+ (child) => extractText(child, acc, indexableNodeTypes)
58
+ );
59
+ }
60
+ };
61
+ const relativePath = (path, collection) => {
62
+ return path.replace(/\\/g, "/").replace(collection.path, "").replace(/^\/|\/$/g, "");
63
+ };
64
+ const tokenizeString = (str) => {
65
+ return str.split(/[\s\.,]+/).map((s) => s.toLowerCase()).filter((s) => s);
66
+ };
67
+ const processTextFieldValue = (value, maxLen) => {
68
+ const tokens = tokenizeString(value);
69
+ const builder = new StringBuilder(maxLen);
70
+ for (const part of tokens) {
71
+ if (builder.append(part)) {
72
+ break;
73
+ }
74
+ }
75
+ return builder.toString();
76
+ };
77
+ const processDocumentForIndexing = (data, path, collection, textIndexLength, field) => {
78
+ if (!field) {
79
+ const relPath = relativePath(path, collection);
80
+ data["_id"] = `${collection.name}:${relPath}`;
81
+ data["_relativePath"] = relPath;
82
+ }
83
+ for (const f of (field == null ? void 0 : field.fields) || collection.fields || []) {
84
+ if (!f.searchable) {
85
+ delete data[f.name];
86
+ continue;
87
+ }
88
+ const isList = f.list;
89
+ if (data[f.name]) {
90
+ if (f.type === "object") {
91
+ if (isList) {
92
+ data[f.name] = data[f.name].map(
93
+ (obj) => processDocumentForIndexing(
94
+ obj,
95
+ path,
96
+ collection,
97
+ textIndexLength,
98
+ f
99
+ )
100
+ );
101
+ } else {
102
+ data[f.name] = processDocumentForIndexing(
103
+ data[f.name],
104
+ path,
105
+ collection,
106
+ textIndexLength,
107
+ f
108
+ );
109
+ }
110
+ } else if (f.type === "string") {
111
+ const fieldTextIndexLength = f.maxSearchIndexFieldLength || textIndexLength;
112
+ if (isList) {
113
+ data[f.name] = data[f.name].map(
114
+ (value) => processTextFieldValue(value, fieldTextIndexLength)
115
+ );
116
+ } else {
117
+ data[f.name] = processTextFieldValue(
118
+ data[f.name],
119
+ fieldTextIndexLength
120
+ );
121
+ }
122
+ } else if (f.type === "rich-text") {
123
+ const fieldTextIndexLength = f.maxSearchIndexFieldLength || textIndexLength;
124
+ if (isList) {
125
+ data[f.name] = data[f.name].map((value) => {
126
+ const acc = new StringBuilder(fieldTextIndexLength);
127
+ extractText(value, acc, ["text", "code_block", "html"]);
128
+ return acc.toString();
129
+ });
130
+ } else {
131
+ const acc = new StringBuilder(fieldTextIndexLength);
132
+ extractText(data[f.name], acc, ["text", "code_block", "html"]);
133
+ data[f.name] = acc.toString();
134
+ }
135
+ }
136
+ }
137
+ }
138
+ return data;
139
+ };
140
+ const memo = {};
141
+ const lookupStopwords = (keys, defaultStopWords = sw__namespace.eng) => {
142
+ let stopwords = defaultStopWords;
143
+ if (keys) {
144
+ if (memo[keys.join(",")]) {
145
+ return memo[keys.join(",")];
146
+ }
147
+ stopwords = [];
148
+ for (const key of keys) {
149
+ stopwords.push(...sw__namespace[key]);
150
+ }
151
+ memo[keys.join(",")] = stopwords;
152
+ }
153
+ return stopwords;
154
+ };
155
+ const queryToSearchIndexQuery = (query, stopwordLanguages) => {
156
+ let q;
157
+ const parts = query.split(" ");
158
+ const stopwords = lookupStopwords(stopwordLanguages);
159
+ if (parts.length === 1) {
160
+ q = { AND: [parts[0]] };
161
+ } else {
162
+ q = {
163
+ AND: parts.filter(
164
+ (part) => part.toLowerCase() !== "and" && stopwords.indexOf(part.toLowerCase()) === -1
165
+ )
166
+ };
167
+ }
168
+ return q;
169
+ };
170
+ const optionsToSearchIndexOptions = (options) => {
171
+ const opt = {};
172
+ if (options == null ? void 0 : options.limit) {
173
+ opt["PAGE"] = {
174
+ SIZE: options.limit,
175
+ NUMBER: (options == null ? void 0 : options.cursor) ? parseInt(options.cursor) : 0
176
+ };
177
+ }
178
+ return opt;
179
+ };
180
+ const parseSearchIndexResponse = (data, options) => {
181
+ const results = data["RESULT"];
182
+ const total = data["RESULT_LENGTH"];
183
+ if ((options == null ? void 0 : options.cursor) && (options == null ? void 0 : options.limit)) {
184
+ const prevCursor = options.cursor === "0" ? null : (parseInt(options.cursor) - 1).toString();
185
+ const nextCursor = total <= (parseInt(options.cursor) + 1) * options.limit ? null : (parseInt(options.cursor) + 1).toString();
186
+ return {
187
+ results,
188
+ total,
189
+ prevCursor,
190
+ nextCursor
191
+ };
192
+ } else if (!(options == null ? void 0 : options.cursor) && (options == null ? void 0 : options.limit)) {
193
+ const prevCursor = null;
194
+ const nextCursor = total <= options.limit ? null : "1";
195
+ return {
196
+ results,
197
+ total,
198
+ prevCursor,
199
+ nextCursor
200
+ };
201
+ } else {
202
+ return {
203
+ results,
204
+ total,
205
+ prevCursor: null,
206
+ nextCursor: null
207
+ };
208
+ }
209
+ };
210
+ exports2.optionsToSearchIndexOptions = optionsToSearchIndexOptions;
211
+ exports2.parseSearchIndexResponse = parseSearchIndexResponse;
212
+ exports2.processDocumentForIndexing = processDocumentForIndexing;
213
+ exports2.queryToSearchIndexQuery = queryToSearchIndexQuery;
214
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
215
+ });
@@ -0,0 +1,195 @@
1
+ import * as sw from "stopword";
2
+ class StringBuilder {
3
+ constructor(limit) {
4
+ this.length = 0;
5
+ this.buffer = [];
6
+ this.limit = limit;
7
+ }
8
+ append(str) {
9
+ if (this.length + str.length > this.limit) {
10
+ return true;
11
+ } else {
12
+ this.buffer.push(str);
13
+ this.length += str.length;
14
+ if (this.length > this.limit) {
15
+ return true;
16
+ }
17
+ return false;
18
+ }
19
+ }
20
+ toString() {
21
+ return this.buffer.join(" ");
22
+ }
23
+ }
24
+ const extractText = (data, acc, indexableNodeTypes) => {
25
+ var _a, _b;
26
+ if (data) {
27
+ if (indexableNodeTypes.indexOf(data.type) !== -1 && (data.text || data.value)) {
28
+ const tokens = tokenizeString(data.text || data.value);
29
+ for (const token of tokens) {
30
+ if (acc.append(token)) {
31
+ return;
32
+ }
33
+ }
34
+ }
35
+ (_b = (_a = data.children) == null ? void 0 : _a.forEach) == null ? void 0 : _b.call(
36
+ _a,
37
+ (child) => extractText(child, acc, indexableNodeTypes)
38
+ );
39
+ }
40
+ };
41
+ const relativePath = (path, collection) => {
42
+ return path.replace(/\\/g, "/").replace(collection.path, "").replace(/^\/|\/$/g, "");
43
+ };
44
+ const tokenizeString = (str) => {
45
+ return str.split(/[\s\.,]+/).map((s) => s.toLowerCase()).filter((s) => s);
46
+ };
47
+ const processTextFieldValue = (value, maxLen) => {
48
+ const tokens = tokenizeString(value);
49
+ const builder = new StringBuilder(maxLen);
50
+ for (const part of tokens) {
51
+ if (builder.append(part)) {
52
+ break;
53
+ }
54
+ }
55
+ return builder.toString();
56
+ };
57
+ const processDocumentForIndexing = (data, path, collection, textIndexLength, field) => {
58
+ if (!field) {
59
+ const relPath = relativePath(path, collection);
60
+ data["_id"] = `${collection.name}:${relPath}`;
61
+ data["_relativePath"] = relPath;
62
+ }
63
+ for (const f of (field == null ? void 0 : field.fields) || collection.fields || []) {
64
+ if (!f.searchable) {
65
+ delete data[f.name];
66
+ continue;
67
+ }
68
+ const isList = f.list;
69
+ if (data[f.name]) {
70
+ if (f.type === "object") {
71
+ if (isList) {
72
+ data[f.name] = data[f.name].map(
73
+ (obj) => processDocumentForIndexing(
74
+ obj,
75
+ path,
76
+ collection,
77
+ textIndexLength,
78
+ f
79
+ )
80
+ );
81
+ } else {
82
+ data[f.name] = processDocumentForIndexing(
83
+ data[f.name],
84
+ path,
85
+ collection,
86
+ textIndexLength,
87
+ f
88
+ );
89
+ }
90
+ } else if (f.type === "string") {
91
+ const fieldTextIndexLength = f.maxSearchIndexFieldLength || textIndexLength;
92
+ if (isList) {
93
+ data[f.name] = data[f.name].map(
94
+ (value) => processTextFieldValue(value, fieldTextIndexLength)
95
+ );
96
+ } else {
97
+ data[f.name] = processTextFieldValue(
98
+ data[f.name],
99
+ fieldTextIndexLength
100
+ );
101
+ }
102
+ } else if (f.type === "rich-text") {
103
+ const fieldTextIndexLength = f.maxSearchIndexFieldLength || textIndexLength;
104
+ if (isList) {
105
+ data[f.name] = data[f.name].map((value) => {
106
+ const acc = new StringBuilder(fieldTextIndexLength);
107
+ extractText(value, acc, ["text", "code_block", "html"]);
108
+ return acc.toString();
109
+ });
110
+ } else {
111
+ const acc = new StringBuilder(fieldTextIndexLength);
112
+ extractText(data[f.name], acc, ["text", "code_block", "html"]);
113
+ data[f.name] = acc.toString();
114
+ }
115
+ }
116
+ }
117
+ }
118
+ return data;
119
+ };
120
+ const memo = {};
121
+ const lookupStopwords = (keys, defaultStopWords = sw.eng) => {
122
+ let stopwords = defaultStopWords;
123
+ if (keys) {
124
+ if (memo[keys.join(",")]) {
125
+ return memo[keys.join(",")];
126
+ }
127
+ stopwords = [];
128
+ for (const key of keys) {
129
+ stopwords.push(...sw[key]);
130
+ }
131
+ memo[keys.join(",")] = stopwords;
132
+ }
133
+ return stopwords;
134
+ };
135
+ const queryToSearchIndexQuery = (query, stopwordLanguages) => {
136
+ let q;
137
+ const parts = query.split(" ");
138
+ const stopwords = lookupStopwords(stopwordLanguages);
139
+ if (parts.length === 1) {
140
+ q = { AND: [parts[0]] };
141
+ } else {
142
+ q = {
143
+ AND: parts.filter(
144
+ (part) => part.toLowerCase() !== "and" && stopwords.indexOf(part.toLowerCase()) === -1
145
+ )
146
+ };
147
+ }
148
+ return q;
149
+ };
150
+ const optionsToSearchIndexOptions = (options) => {
151
+ const opt = {};
152
+ if (options == null ? void 0 : options.limit) {
153
+ opt["PAGE"] = {
154
+ SIZE: options.limit,
155
+ NUMBER: (options == null ? void 0 : options.cursor) ? parseInt(options.cursor) : 0
156
+ };
157
+ }
158
+ return opt;
159
+ };
160
+ const parseSearchIndexResponse = (data, options) => {
161
+ const results = data["RESULT"];
162
+ const total = data["RESULT_LENGTH"];
163
+ if ((options == null ? void 0 : options.cursor) && (options == null ? void 0 : options.limit)) {
164
+ const prevCursor = options.cursor === "0" ? null : (parseInt(options.cursor) - 1).toString();
165
+ const nextCursor = total <= (parseInt(options.cursor) + 1) * options.limit ? null : (parseInt(options.cursor) + 1).toString();
166
+ return {
167
+ results,
168
+ total,
169
+ prevCursor,
170
+ nextCursor
171
+ };
172
+ } else if (!(options == null ? void 0 : options.cursor) && (options == null ? void 0 : options.limit)) {
173
+ const prevCursor = null;
174
+ const nextCursor = total <= options.limit ? null : "1";
175
+ return {
176
+ results,
177
+ total,
178
+ prevCursor,
179
+ nextCursor
180
+ };
181
+ } else {
182
+ return {
183
+ results,
184
+ total,
185
+ prevCursor: null,
186
+ nextCursor: null
187
+ };
188
+ }
189
+ };
190
+ export {
191
+ optionsToSearchIndexOptions,
192
+ parseSearchIndexResponse,
193
+ processDocumentForIndexing,
194
+ queryToSearchIndexQuery
195
+ };
@@ -0,0 +1,5 @@
1
+ import si from 'search-index';
2
+ export { SearchIndexer } from './indexer';
3
+ export { LocalSearchIndexClient, TinaCMSSearchIndexClient } from './client';
4
+ export type { SearchClient } from './types';
5
+ export { si };
package/dist/index.js ADDED
@@ -0,0 +1,364 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
21
+ mod
22
+ ));
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+
25
+ // src/index.ts
26
+ var src_exports = {};
27
+ __export(src_exports, {
28
+ LocalSearchIndexClient: () => LocalSearchIndexClient,
29
+ SearchIndexer: () => SearchIndexer,
30
+ TinaCMSSearchIndexClient: () => TinaCMSSearchIndexClient,
31
+ si: () => import_search_index2.default
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+ var import_search_index2 = __toESM(require("search-index"));
35
+
36
+ // src/indexer/index.ts
37
+ var import_graphql = require("@tinacms/graphql");
38
+
39
+ // src/indexer/utils.ts
40
+ var sw = __toESM(require("stopword"));
41
+ var StringBuilder = class {
42
+ constructor(limit) {
43
+ this.length = 0;
44
+ this.buffer = [];
45
+ this.limit = limit;
46
+ }
47
+ append(str) {
48
+ if (this.length + str.length > this.limit) {
49
+ return true;
50
+ } else {
51
+ this.buffer.push(str);
52
+ this.length += str.length;
53
+ if (this.length > this.limit) {
54
+ return true;
55
+ }
56
+ return false;
57
+ }
58
+ }
59
+ toString() {
60
+ return this.buffer.join(" ");
61
+ }
62
+ };
63
+ var extractText = (data, acc, indexableNodeTypes) => {
64
+ var _a, _b;
65
+ if (data) {
66
+ if (indexableNodeTypes.indexOf(data.type) !== -1 && (data.text || data.value)) {
67
+ const tokens = tokenizeString(data.text || data.value);
68
+ for (const token of tokens) {
69
+ if (acc.append(token)) {
70
+ return;
71
+ }
72
+ }
73
+ }
74
+ (_b = (_a = data.children) == null ? void 0 : _a.forEach) == null ? void 0 : _b.call(
75
+ _a,
76
+ (child) => extractText(child, acc, indexableNodeTypes)
77
+ );
78
+ }
79
+ };
80
+ var relativePath = (path, collection) => {
81
+ return path.replace(/\\/g, "/").replace(collection.path, "").replace(/^\/|\/$/g, "");
82
+ };
83
+ var tokenizeString = (str) => {
84
+ return str.split(/[\s\.,]+/).map((s) => s.toLowerCase()).filter((s) => s);
85
+ };
86
+ var processTextFieldValue = (value, maxLen) => {
87
+ const tokens = tokenizeString(value);
88
+ const builder = new StringBuilder(maxLen);
89
+ for (const part of tokens) {
90
+ if (builder.append(part)) {
91
+ break;
92
+ }
93
+ }
94
+ return builder.toString();
95
+ };
96
+ var processDocumentForIndexing = (data, path, collection, textIndexLength, field) => {
97
+ if (!field) {
98
+ const relPath = relativePath(path, collection);
99
+ data["_id"] = `${collection.name}:${relPath}`;
100
+ data["_relativePath"] = relPath;
101
+ }
102
+ for (const f of (field == null ? void 0 : field.fields) || collection.fields || []) {
103
+ if (!f.searchable) {
104
+ delete data[f.name];
105
+ continue;
106
+ }
107
+ const isList = f.list;
108
+ if (data[f.name]) {
109
+ if (f.type === "object") {
110
+ if (isList) {
111
+ data[f.name] = data[f.name].map(
112
+ (obj) => processDocumentForIndexing(
113
+ obj,
114
+ path,
115
+ collection,
116
+ textIndexLength,
117
+ f
118
+ )
119
+ );
120
+ } else {
121
+ data[f.name] = processDocumentForIndexing(
122
+ data[f.name],
123
+ path,
124
+ collection,
125
+ textIndexLength,
126
+ f
127
+ );
128
+ }
129
+ } else if (f.type === "string") {
130
+ const fieldTextIndexLength = f.maxSearchIndexFieldLength || textIndexLength;
131
+ if (isList) {
132
+ data[f.name] = data[f.name].map(
133
+ (value) => processTextFieldValue(value, fieldTextIndexLength)
134
+ );
135
+ } else {
136
+ data[f.name] = processTextFieldValue(
137
+ data[f.name],
138
+ fieldTextIndexLength
139
+ );
140
+ }
141
+ } else if (f.type === "rich-text") {
142
+ const fieldTextIndexLength = f.maxSearchIndexFieldLength || textIndexLength;
143
+ if (isList) {
144
+ data[f.name] = data[f.name].map((value) => {
145
+ const acc = new StringBuilder(fieldTextIndexLength);
146
+ extractText(value, acc, ["text", "code_block", "html"]);
147
+ return acc.toString();
148
+ });
149
+ } else {
150
+ const acc = new StringBuilder(fieldTextIndexLength);
151
+ extractText(data[f.name], acc, ["text", "code_block", "html"]);
152
+ data[f.name] = acc.toString();
153
+ }
154
+ }
155
+ }
156
+ }
157
+ return data;
158
+ };
159
+ var memo = {};
160
+ var lookupStopwords = (keys, defaultStopWords = sw.eng) => {
161
+ let stopwords = defaultStopWords;
162
+ if (keys) {
163
+ if (memo[keys.join(",")]) {
164
+ return memo[keys.join(",")];
165
+ }
166
+ stopwords = [];
167
+ for (const key of keys) {
168
+ stopwords.push(...sw[key]);
169
+ }
170
+ memo[keys.join(",")] = stopwords;
171
+ }
172
+ return stopwords;
173
+ };
174
+
175
+ // src/indexer/index.ts
176
+ var SearchIndexer = class {
177
+ constructor(options) {
178
+ this.client = options.client;
179
+ this.bridge = options.bridge;
180
+ this.schema = options.schema;
181
+ this.batchSize = options.batchSize || 100;
182
+ this.textIndexLength = options.textIndexLength || 500;
183
+ }
184
+ makeIndexerCallback(itemCallback) {
185
+ return async (collection, contentPaths) => {
186
+ const templateInfo = this.schema.getTemplatesForCollectable(collection);
187
+ await (0, import_graphql.sequential)(contentPaths, async (path) => {
188
+ const data = await (0, import_graphql.transformDocumentIntoPayload)(
189
+ `${collection.path}/${path}`,
190
+ (0, import_graphql.transformDocument)(
191
+ path,
192
+ await (0, import_graphql.loadAndParseWithAliases)(
193
+ this.bridge,
194
+ path,
195
+ collection,
196
+ templateInfo
197
+ ),
198
+ this.schema
199
+ ),
200
+ this.schema
201
+ );
202
+ await itemCallback(
203
+ processDocumentForIndexing(
204
+ data["_values"],
205
+ path,
206
+ collection,
207
+ this.textIndexLength
208
+ )
209
+ );
210
+ });
211
+ };
212
+ }
213
+ async indexContentByPaths(documentPaths) {
214
+ var _a, _b, _c, _d;
215
+ let batch = [];
216
+ const itemCallback = async (item) => {
217
+ batch.push(item);
218
+ if (batch.length > this.batchSize) {
219
+ await this.client.put(batch);
220
+ batch = [];
221
+ }
222
+ };
223
+ await ((_b = (_a = this.client).onStartIndexing) == null ? void 0 : _b.call(_a));
224
+ await (0, import_graphql.scanContentByPaths)(
225
+ this.schema,
226
+ documentPaths,
227
+ this.makeIndexerCallback(itemCallback)
228
+ );
229
+ if (batch.length > 0) {
230
+ await this.client.put(batch);
231
+ }
232
+ await ((_d = (_c = this.client).onFinishIndexing) == null ? void 0 : _d.call(_c));
233
+ }
234
+ async indexAllContent() {
235
+ var _a, _b, _c, _d;
236
+ await ((_b = (_a = this.client).onStartIndexing) == null ? void 0 : _b.call(_a));
237
+ let batch = [];
238
+ const itemCallback = async (item) => {
239
+ batch.push(item);
240
+ if (batch.length > this.batchSize) {
241
+ await this.client.put(batch);
242
+ batch = [];
243
+ }
244
+ };
245
+ const warnings = await (0, import_graphql.scanAllContent)(
246
+ this.schema,
247
+ this.bridge,
248
+ this.makeIndexerCallback(itemCallback)
249
+ );
250
+ if (batch.length > 0) {
251
+ await this.client.put(batch);
252
+ }
253
+ await ((_d = (_c = this.client).onFinishIndexing) == null ? void 0 : _d.call(_c));
254
+ return { warnings };
255
+ }
256
+ async deleteIndexContent(documentPaths) {
257
+ var _a, _b, _c, _d;
258
+ await ((_b = (_a = this.client).onStartIndexing) == null ? void 0 : _b.call(_a));
259
+ await this.client.del(documentPaths);
260
+ await ((_d = (_c = this.client).onFinishIndexing) == null ? void 0 : _d.call(_c));
261
+ }
262
+ };
263
+
264
+ // src/client/index.ts
265
+ var import_sqlite_level = require("sqlite-level");
266
+ var import_search_index = __toESM(require("search-index"));
267
+ var import_memory_level = require("memory-level");
268
+ var zlib = __toESM(require("zlib"));
269
+ var DEFAULT_TOKEN_SPLIT_REGEX = /[\p{L}\d_]+/gu;
270
+ var LocalSearchIndexClient = class {
271
+ constructor(options) {
272
+ this.memoryLevel = new import_memory_level.MemoryLevel();
273
+ this.stopwords = lookupStopwords(options.stopwordLanguages);
274
+ this.tokenSplitRegex = options.tokenSplitRegex ? new RegExp(options.tokenSplitRegex, "gu") : DEFAULT_TOKEN_SPLIT_REGEX;
275
+ }
276
+ async onStartIndexing() {
277
+ this.searchIndex = await (0, import_search_index.default)({
278
+ db: this.memoryLevel,
279
+ stopwords: this.stopwords,
280
+ tokenSplitRegex: this.tokenSplitRegex
281
+ });
282
+ }
283
+ async put(docs) {
284
+ if (!this.searchIndex) {
285
+ throw new Error("onStartIndexing must be called first");
286
+ }
287
+ return this.searchIndex.PUT(docs);
288
+ }
289
+ async del(ids) {
290
+ if (!this.searchIndex) {
291
+ throw new Error("onStartIndexing must be called first");
292
+ }
293
+ return this.searchIndex.DELETE(ids);
294
+ }
295
+ query(query, options) {
296
+ return Promise.resolve({
297
+ nextCursor: void 0,
298
+ prevCursor: void 0,
299
+ results: [],
300
+ total: 0
301
+ });
302
+ }
303
+ async export(filename) {
304
+ const sqliteLevel = new import_sqlite_level.SqliteLevel({ filename });
305
+ const iterator = this.memoryLevel.iterator();
306
+ for await (const [key, value] of iterator) {
307
+ await sqliteLevel.put(key, value);
308
+ }
309
+ await sqliteLevel.close();
310
+ }
311
+ };
312
+ var TinaCMSSearchIndexClient = class extends LocalSearchIndexClient {
313
+ constructor(options) {
314
+ super(options);
315
+ this.apiUrl = options.apiUrl;
316
+ this.branch = options.branch;
317
+ this.indexerToken = options.indexerToken;
318
+ }
319
+ async onFinishIndexing() {
320
+ const headers = new Headers();
321
+ headers.append("x-api-key", this.indexerToken || "bogus");
322
+ headers.append("Content-Type", "application/json");
323
+ let res = await fetch(`${this.apiUrl}/upload/${this.branch}`, {
324
+ method: "GET",
325
+ headers
326
+ });
327
+ if (res.status !== 200) {
328
+ let json;
329
+ try {
330
+ json = await res.json();
331
+ } catch (e) {
332
+ console.error("Failed to parse error response", e);
333
+ }
334
+ throw new Error(
335
+ `Failed to get upload url. Status: ${res.status}${(json == null ? void 0 : json.message) ? ` - ${json.message}` : ``}`
336
+ );
337
+ }
338
+ const { signedUrl } = await res.json();
339
+ const sqliteLevel = new import_sqlite_level.SqliteLevel({ filename: ":memory:" });
340
+ const iterator = this.memoryLevel.iterator();
341
+ for await (const [key, value] of iterator) {
342
+ await sqliteLevel.put(key, value);
343
+ }
344
+ const buffer = sqliteLevel.db.serialize();
345
+ await sqliteLevel.close();
346
+ res = await fetch(signedUrl, {
347
+ method: "PUT",
348
+ body: zlib.gzipSync(buffer)
349
+ });
350
+ if (res.status !== 200) {
351
+ throw new Error(
352
+ `Failed to upload search index. Status: ${res.status}
353
+ ${await res.text()}`
354
+ );
355
+ }
356
+ }
357
+ };
358
+ // Annotate the CommonJS export names for ESM import in node:
359
+ 0 && (module.exports = {
360
+ LocalSearchIndexClient,
361
+ SearchIndexer,
362
+ TinaCMSSearchIndexClient,
363
+ si
364
+ });
@@ -0,0 +1,25 @@
1
+ import { TinaSchema } from '@tinacms/schema-tools';
2
+ import { Bridge } from '@tinacms/graphql';
3
+ import { SearchClient } from '../types';
4
+ type SearchIndexOptions = {
5
+ batchSize?: number;
6
+ bridge: Bridge;
7
+ client: SearchClient;
8
+ schema: TinaSchema;
9
+ textIndexLength?: number;
10
+ };
11
+ export declare class SearchIndexer {
12
+ private readonly batchSize;
13
+ private readonly client;
14
+ private readonly bridge;
15
+ private readonly schema;
16
+ private readonly textIndexLength;
17
+ constructor(options: SearchIndexOptions);
18
+ private makeIndexerCallback;
19
+ indexContentByPaths(documentPaths: string[]): Promise<void>;
20
+ indexAllContent(): Promise<{
21
+ warnings: string[];
22
+ }>;
23
+ deleteIndexContent(documentPaths: string[]): Promise<void>;
24
+ }
25
+ export {};
@@ -0,0 +1,3 @@
1
+ import { Collection, ObjectField } from '@tinacms/schema-tools';
2
+ export declare const processDocumentForIndexing: (data: any, path: string, collection: Collection, textIndexLength: number, field?: ObjectField) => any;
3
+ export declare const lookupStopwords: (keys?: string[], defaultStopWords?: string[]) => string[];
@@ -0,0 +1,16 @@
1
+ export type SearchClient = {
2
+ query: (query: string, options?: {
3
+ cursor?: string;
4
+ limit?: number;
5
+ }) => Promise<{
6
+ results: any[];
7
+ total: number;
8
+ nextCursor: string | null;
9
+ prevCursor: string | null;
10
+ }>;
11
+ put: (docs: any[]) => Promise<any>;
12
+ del: (ids: string[]) => Promise<any>;
13
+ onStartIndexing?: () => Promise<void>;
14
+ onFinishIndexing?: () => Promise<void>;
15
+ supportsClientSideIndexing?: () => boolean;
16
+ };
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@tinacms/search",
3
+ "version": "0.0.0-00f6525-20241015065741",
4
+ "main": "dist/index.js",
5
+ "module": "dist/index-client.mjs",
6
+ "typings": "dist/index.d.ts",
7
+ "files": [
8
+ "package.json",
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.js"
15
+ },
16
+ "./dist/index-client": {
17
+ "import": "./dist/index-client.mjs",
18
+ "require": "./dist/index-client.js"
19
+ }
20
+ },
21
+ "license": "SEE LICENSE IN LICENSE",
22
+ "buildConfig": {
23
+ "entryPoints": [
24
+ {
25
+ "name": "src/index.ts",
26
+ "target": "node"
27
+ },
28
+ "src/index-client.ts"
29
+ ]
30
+ },
31
+ "dependencies": {
32
+ "memory-level": "^1.0.0",
33
+ "search-index": "4.0.0",
34
+ "sqlite-level": "^1.2.0",
35
+ "stopword": "^3.1.1",
36
+ "@tinacms/graphql": "0.0.0-00f6525-20241015065741",
37
+ "@tinacms/schema-tools": "0.0.0-00f6525-20241015065741"
38
+ },
39
+ "publishConfig": {
40
+ "registry": "https://registry.npmjs.org"
41
+ },
42
+ "repository": {
43
+ "url": "https://github.com/tinacms/tinacms.git",
44
+ "directory": "packages/@tinacms/search"
45
+ },
46
+ "devDependencies": {
47
+ "@types/jest": "^29.5.13",
48
+ "@types/micromatch": "^4.0.9",
49
+ "@types/node": "^22.7.4",
50
+ "@types/search-index": "^3.2.4",
51
+ "jest": "^29.7.0",
52
+ "jest-diff": "^29.7.0",
53
+ "jest-file-snapshot": "^0.7.0",
54
+ "jest-matcher-utils": "^29.7.0",
55
+ "typescript": "^5.6.2",
56
+ "@tinacms/scripts": "0.0.0-00f6525-20241015065741"
57
+ },
58
+ "scripts": {
59
+ "types": "pnpm tsc",
60
+ "build": "tinacms-scripts build",
61
+ "docs": "pnpm typedoc",
62
+ "serve": "pnpm nodemon dist/server.js",
63
+ "test": "jest",
64
+ "test-watch": "jest --watch"
65
+ }
66
+ }