26 |
27 |
28 |
--------------------------------------------------------------------------------
/assets/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/internet4000/find/1d224cb549e11aaa760221cfa1819ef19010f3fe/assets/favicon.ico
--------------------------------------------------------------------------------
/assets/find-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/internet4000/find/1d224cb549e11aaa760221cfa1819ef19010f3fe/assets/find-logo.png
--------------------------------------------------------------------------------
/assets/find-logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/assets/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Find!",
3 | "short_name": "Find",
4 | "display": "standalone",
5 | "icon": "./assets/find-logo.svg",
6 | "start_url": "/"
7 | }
8 |
--------------------------------------------------------------------------------
/assets/opensearch.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | UTF-8
4 | Find
5 | Find anything anywhere
6 | https://example.org/i4k-find/assets/favicon.ico
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/docs/deployment.md:
--------------------------------------------------------------------------------
1 | # Deployment
2 | To deploy a new Find instance, as a static website.
3 |
4 | For more customization, see the development documentation.
5 |
6 | ## Methods
7 | There are diverse possibilities to deploy a new instance with a custom
8 | Find, generally it will need the correct values for the `I4K_FIND_URL`
9 | environment variable, `https://example.org/my-find`. As reference,
10 | check the different CI/CD workflow recipes.
11 |
12 | > The recommended method is to use a CI/CD recipe to deploy a custom
13 | > instance, to a custom server (or pages like the default
14 | > insance). That way it regroups the code, the infrastructure that
15 | > deploys it and the server that hosts it together.
16 |
17 | ### Drag and drop on a "static file server"
18 | Because the code of Find has no build pipeline, deploying a new
19 | instance of Find should be as simple as copying the entire `/find`
20 | folder (this repo) on a web server.
21 |
22 | For a "clean deployment", it is better to copy the required files,
23 | into a new folder. See the CI/CD recipes references, which automate
24 | this process by listing the required steps and commands.
25 |
26 | ### static pages from providers
27 | Makes a fork of the project, and deploy to a "static pages provider"
28 | connected with the git repo. There is no `build` step, and the
29 | project's root folder is `.` for the current proejct folder (or `/`
30 | depending on the provider).
31 |
32 | [](https://app.netlify.com/start/deploy?repository=https://github.com/internet4000/find)
34 |
35 | [](https://vercel.com/new/clone?repository-url=https://github.com/internet4000/find)
37 |
38 |
39 | ### github fork & actions (for own instance)
40 | - fork this repository
41 | - enable "pages from actions" in the settings
42 | - customize the `I4K_FIND_URL` env var (it will try to default to the
43 | github pages deployment URL)
44 | - run the "static.yml" workflow
45 | - visit the fork's github page
46 |
47 | ### gitlab pages
48 | - fork this repository on gitlab
49 | - it should use the `pages` job/pipeline, that will deploy a new instance
50 |
51 | Gitlab offfer "private pages", so a page could be accessed only by
52 | users who are logged in to the repo
53 |
54 | ### local/private/VPN instance
55 |
56 | Can run on `localhost:` on any machine, with the dev server
57 | (though maybe something more efficient could be nice).
58 |
59 | Can be served from a "private local machine" (ex: unused phone over
60 | 4g, or raspi), runnin a wireguard VPN or private [Tailscale
61 | Tailnet](https://tailscale.com/kb/1136/tailnet/?q=tailnet).
62 |
63 | That way requests should never leave the user network, until resolved
64 | by Find to a URL that the browser can resolve
65 |
66 |
--------------------------------------------------------------------------------
/docs/development.md:
--------------------------------------------------------------------------------
1 | # Development
2 | To work on new features, bug fixes, tests and prototypes.
3 |
4 | > The project should be able to run locally without the need of a
5 | > developement server, but requires manually fixing the "assets path"
6 | > (CORS error if `file:///.../internet4000/find/index.html` is
7 | > opened).
8 |
9 | >Similarely, an other server can be used than the one provided, ex:
10 | >`python3 -m http.server --directory .` Node.js is currently only
11 | >required for running the tests.
12 |
13 | ## Documentation
14 |
15 | - the javascript file `src/index.js` contains all the code for I4kFind.
16 | - the javascript file `src/ui/index.js` contains all the code for I4kFind web-components, composing the graphical user interface
17 |
18 | > The web-components are only loaded after the find logic, if the user
19 | > stays on the page (if there is no user query).
20 |
21 | > Find does not have any production dependency, uses vanilla javascript, html
22 | > and css code, that runs only in the user's browser tab.
23 |
24 | ## General
25 |
26 |
27 | - `npm install` to get the development dependencies (there are, and
28 | should be, no production dependencies)
29 | - `npm start` to run the local server (it should say at which URL the
30 | page is locally available)
31 | - There is no build system, to keep things small, simple and
32 | accessible; so the folder can be deployed as it is onto a web
33 | server, or after any change has been made (and we're satisfied with
34 | them).
35 |
36 | All the Find logic code, is located in the folder `/src/index.js`. It
37 | does not, and should not import other files.
38 |
39 | Other files are configuration files for the continous
40 | integration, testing, opensearch, hosting.
41 |
42 | > Notes the URL's root `/` are the base of the find instance, or of the
43 | > project folder depending on the context.
44 |
45 | ## NPM package
46 | Find is available as a javascript es6 NPM module [!npm
47 | i4k-find](https://www.npmjs.com/package/i4k-find).
48 |
49 | ### Install
50 | In a new project use `npm instal i4k-find`.
51 |
52 | ```js
53 | import find from "https://cdn.jsdelivr.net/npm/i4k-find@latest";
54 |
55 | const openWindow = false; ;; defaults to true
56 | const userQuery = "&gh internet4000 find"
57 | const queryResult = find.find(userQuery, openWindow)
58 | console.info(queryResult)
59 | ```
60 |
61 | ### Publish as a package
62 | It uses a github workflow to run `npm publish` when a new tag is
63 | created, for example `0.0.10`, which should match the value of the
64 | `package.json.version` (and not already but published with this
65 | version on npm).
66 |
67 | ## Node.js CLI utility
68 | To get a Find result from a shell, in node.js. Can run for example:
69 | - `node ../com.github/internet4000/find/src/scripts/i4k-find.js "&gh
70 | i4k find"` (if downloaded loacally, from an other folder)
71 | - `npx i4k-find "my query in bash string"`, directly from npm
72 | - `npm link i4k-find` or `npm link ` (to test locally)
73 | - `npm run find "hello"` when developing in this repo (`package.json.scripts.fin`)
74 | - as a [shell alias](https://en.wikipedia.org/wiki/Alias_%28command%29)
75 |
76 | It is possible to bind i4k-find to a "shell environment variable", to
77 | use Find from a shortcut, and pipe its output to other program (ex:
78 | browser open URL of the result), or pipe other program's input to it.
79 |
80 | > Running from the shell, should only output the "translated query";
81 | > and liberty to the user to "pipe" this output to an other unix
82 | > utility (maybe open in a browser)
83 |
84 | ```txt
85 | # feed "text string" to Find as arguments
86 | echo hello | xargs npx i4k-find
87 | npx i4k-find "&gh internet4000 find" | firefox
88 | # the previous is currently not working @TODO
89 | ```
90 |
91 | > `xargs` is a unix utility to convert "stdin" to "arguments" in a
92 | > shell. Find is trying to be "isomorphic" without build tool, getting
93 | > to read stdin input in node.js requires to import readline
94 |
95 | > Note: it could be improved to allow calling more or its "methods"
96 | > from the CLI, or be passed arugments (more than the default `q`
97 | > query string), such as --json, to get a for detailed "parsing result
98 | > answer" (also see i4k npm pkg media-url-parser).
99 |
100 | From a `queries.txt` file with the content:
101 | ```txt
102 | &gh internet4000 find
103 | +space hello world
104 | +data-json {"my_boolean": true}
105 | ```
106 |
107 | The following could be used to generate a Find result for each line:
108 | ```shell
109 | cat queries.txt | npx i4k-find
110 | # will output
111 | https://github.com/internet4000/find
112 | https://goog.space/#input=hello%20world
113 | data:application/json;charset=utf-8,%7B%22my_boolean%22%3A%20true%7D
114 | # there is a newline charater at the end of the output (@TODO: rm)
115 | ```
116 |
117 | Notes: Not sure about many things here:
118 | - new lines `\n`, insert or not? difference with `ls` output
119 | - how to best pipe out to other programs? pipe in to recieve from
120 | other programs, or user input `npx i4k-find "hello"` versus `npx i4k-find` then `hello \n world \n +space test \n +m tokyo \n C-d / C-d`
121 | - how to best read from files
122 | - how to best pass the result to the browser CLI command, to open a
123 | new tab with the result, or multiple tabs per "line result" ?
124 |
125 | ## Testing
126 | To run the tests, after having done `npm install` to get the initial
127 | dependencies, and `npm run test` to run the tests once.
128 |
129 | See [ava's documentation](https://github.com/avajs/ava) for usage.
130 |
131 | ## Sync
132 | Could try to auto sync user defined engines, by "submitting all
133 | changes" to a hidden update-password-form, and submit it.
134 |
135 | Maybe that would triger the browser/password-manager to update the password value for this site.
136 |
137 | ## URLs
138 |
139 | The "base URL of the site" should of the format (window.location, with
140 | no hash or search param, though if only look for one search param
141 | value, `q` for user `query`):
142 | - https://example.org/my-find/
143 | - https://subdomain.example.org/my-find/
144 | - https://subdomain.example.org/my-find/foo/
145 | - https://0.0.0.0:4000/my-find/foo/
146 |
147 | > These URLs can, or not, have a trailling slash `/`
148 |
149 | There we can build these URLs for the user search query (if the param is customized to `my-custom-param`)
150 | - https://example.org/my-find/#my-custom-param=my%20query
151 | - https://subdomain.example.org/my-find/#my-custom-param=my%20query
152 | - https://subdomain.example.org/my-find/foo/#my-custom-param=my%20query
153 | - https://0.0.0.0:4000/my-find/foo/#my-custom-param=my%20query
154 |
155 | ## Open Search file generation
156 | We're trying to (auto)generate an Open Search (Description) file, that
157 | is corect for each deployment context. That way a user can clone/fork
158 | the repo, setup the "one ENV var" (if we cannot get it in our
159 | scripts), and the deployment && XML file (and all config) would be
160 | correct.
161 |
162 | The generation is done by the file `src/scripts/opensearch-xml.js`,
163 | which can be called with the command `npm run opensearch`, (and is run
164 | for each new deploy in the CI/CD recipes).
165 |
166 | This should generate the correct `opensearch.xml`, from information
167 | that the scripts finds from the `package.json` file and `"i4k-find"`
168 | key. As reference, check the project's own.
169 |
170 | ```shell
171 | export I4K_FIND_URL=https://example.org/i4k-find
172 | npm run opensearch
173 | # assets/opensearch.xml
174 | ```
175 |
176 | ## Open Search Suggestions API
177 | The objective with the "service-worker client-side API", is to allow Find
178 | to give feedback, directly in the URL bar, while typing.
179 |
180 | ### Usage
181 | When installed as the default search engine, Find could offer
182 | suggestions, since the browser is supposed to call the suggestions API
183 | endpoint defined in the =opensearch.xml= file.
184 |
185 | If the "find deployment page of your default search engine", has been
186 | visited once, the web-worker.js is loaded, and can maybe execute code,
187 | even while the tab is closed (as it has been register).
188 |
189 | The function of the web-worker, is it catch (middle man), all queries
190 | that are made (all change of characters in the input), and provide
191 | suggestions of search results for the current user input value (in the
192 | URL bar directly).
193 |
194 | Find is setup to always get the data from the hash parameter, which is
195 | the part of the URL that is not sent to the server.
196 |
197 | If we open the browser developper tools, and inspect the network
198 | requests made by a search query (from example in the UI search
199 | input). We can see that no data goes to the server in the Headers or
200 | in the Body of the request.
201 |
202 | > Note: we should probably make a test with wireshark and tcpdump, and
203 | > look at the output of the queries we make (in the browser, via all
204 | > Find methods), to see if any data is leaking out of the browser tab,
205 | > into internet/the-networks. Probably also check with a
206 | > node/python/.. script, to see what their server's can catch from our
207 | > requests. Also if the web-worker is not (yet) registered.
208 |
209 | ### References
210 | - https://developer.mozilla.org/en-US/docs/Web/OpenSearch
211 | - https://gist.github.com/eklem/453dea31bf92d7bf6564
212 |
213 | ### What to try
214 | We're currently only generatig suggestions for the avaiable default
215 | and user engines.
216 |
217 | It would be nice to find a way to have a general, and specific methods
218 | (for each symbol, engine etc.), to seart getting suggestions directly
219 | from their content.
220 |
221 | Maybe:
222 | - use their opensearch file, if they have one, and we can get data
223 | there (make a search query to their search/suggestion endpoint?)
224 |
225 | open `about:debugging` (from the application dev tools tab, for
226 | accessing the service worker's console, debugging etc.)
227 |
228 | ## Visiting the find URL
229 | It is visited each time a search is made.
230 |
231 | We try to only execute the user query part of the script, and not load
232 | any other file/assets if there is any, for speed.
233 |
234 | So the UI part (web components) only loads if find does not need to
235 | redirect to the final page requested by the user.
236 |
237 | Also, as a utility for "other internet protocols", Find tries to
238 | "polyfill" different protocols with a "proxy/gateway".
239 |
240 | `gopher://gopher.floodgap.com`
241 | `gemini://kennedy.gemi.dev`
242 | `spartan://spartan.mozz.us`
243 | `finger://happynetbox.com`
244 | `text://txt.textprotocol.org`
245 | `git://txt.textprotocol.org`
246 | `<:>/>`
247 |
248 | Where `//` is the default "engine used by the protocol, and the
249 | protocol symbol ID is the value of `new URL(//).protocol`.
250 |
251 | So to overvwritte the protocol proxy **web** app (protocol http(s) to
252 | protocol ``), we need to overvwritte its engine `//` (the
253 | default "web-to-protocol proxy").
254 |
255 | ## Adding symbols
256 | It is possible to edit the code and add new symbols.
257 |
258 | For example, adding the `?` symbol does not work, because the browser
259 | treat it as a special reserved character since it builds the _search
260 | param_ part of a URI.
261 |
262 | To test if a new symbol can work, try a new "omnibox search" (not just
263 | a Find input search), and see if the resulting "default search page",
264 | contains the exact query that was first inputed. If the resulting
265 | search includes all characters, then the first one (or `:`)
266 | can be treated as a _symbol_ since the browser does not catch it (find
267 | has the opportunity to do).
268 |
269 | ## Questions
270 | To be investigated.
271 |
272 | ### symbols interpretation and combination
273 | Some questions about `symbols` and their lexical interpretation,
274 | combination, and execution (build & open URL currently).
275 |
276 | The pipe `|` symbol/operator? maybe to pipe the current url (or data)
277 | as input, to other Find symbols, in the same query.
278 |
279 | "If first symbol is `|` pipe" or/and "if last symbol is `|` pipe";
280 |
281 | ```txt
282 | # the user is on current URL: https://example.org
283 | |https://example.org >
284 | ||+space|+qrcode|+share-link
285 | ||+|+qrcode|+share-link
286 | |!sheet |&sheet-json
287 | ```
288 |
289 | These could be saved as user/default defined "combinators" and
290 | function, to manipulate the data and URL they contain, and their app
291 | generates
292 |
293 | ```txt
294 | ## if a pipe `|` symbol existed
295 | #add | note2space2qr |+space {}|+qrcode
296 | ## or if a #add-pipe "helper public user function" existed
297 | #
298 | ```
299 |
300 | Could that do somehing interesting?
301 |
302 | Generally, a bit like shell or [reverse polish
303 | notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation) or
304 | list based programming languages, could, from the URL, build things.
305 |
306 | Using the "local suggestion api" (see web-worker) and maybe [browser
307 | client side
308 | storage](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage), there could be interesting applications.
309 |
310 | ### i4k-find URI scheme
311 |
312 | To represent a find query and what to expect; ref:
313 | https://en.wikipedia.org/wiki/List_of_URI_schemes
314 |
315 | ```txt
316 | i4k-find://host[:port][;/#=]
317 | ;; https://host[:port][;/#=]
318 | ;; file://host[:port][;/#=]
319 | ```
320 |
321 | > with a `#` param, its value should not be sent by the client
322 | > (accessing the URL), to the server (serving the document, pointed by
323 | > this URL). But the client should use the hash param value, with the
324 | > document (code/data) returned by the server
325 |
326 | Could also imagine (if we trust the server):
327 | ```txt
328 | i4k-find://host[:port]/
329 | i4k-find://host[:port]///
330 | i4k-find://host[:port]///
331 | ```
332 |
333 | Where `` and `` are utf-8 text strings, without
334 | spaces, and query is also a string but can contain any characters.
335 |
336 | In the case of find symbols and engines, where the engine URL, is a
337 | "non-standardly accesible URL" (ex:
338 | `data:application/json;charset=utf-8,{}`), we could also use a Find
339 | URI scheme, to return a `i4k-find://` prefix. Find could therefore
340 | figure that it needs to be called again, to interpret a query again.
341 |
342 | As an alternative, `window.location` is the equivalent if the current
343 | Find client needs to check if the user request should be re-analyzed
344 | by Find.
345 |
346 |
347 | ## Links & refs
348 | References, links and inspirations:
349 | - https://en.wikipedia.org/wiki/OpenSearch
350 | - https://duckduckgo.com/bangs
351 | - https://searx.netzspielplatz.de/info/en/search-syntax
352 | - https://en.wikipedia.org/wiki/Searx
353 | - https://en.wikipedia.org/wiki/Metasearch_engine
354 | - https://github.com/arkenfox/user.js
355 | - https://kb.mozillazine.org/User.js_file
356 | - https://mozilla-services.readthedocs.io/en/latest/howtos/run-fxa.html
357 | - https://nyxt.atlas.engineer
358 | - https://docs.ipfs.tech/how-to/address-ipfs-on-web
359 | - https://en.wikipedia.org/wiki/Web_Ontology_Language
360 | - https://en.wikipedia.org/wiki/APL_(programming_language)
361 | - https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
362 | - https://en.wikipedia.org/wiki/List_of_URI_schemes
363 | - https://en.wikipedia.org/wiki/Menu_(computing)
364 | - https://en.wikipedia.org/wiki/Command-line_interface
365 | - https://en.wikipedia.org/wiki/Alias_%28command%29
366 | - https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
367 | - https://developer.mozilla.org/en-US/docs/web/http/basics_of_http/data_urls
368 | - https://developer.mozilla.org/en-US/docs/Web/HTML
369 | - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
370 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
371 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
372 | - https://console.spec.whatwg.org/#formatter (DOM+CSS+JS Object parsing)
373 | - https://spec.matrix.org/v1.7/appendices/#common-namespaced-identifier-grammar
374 | - https://www.w3.org/People/Berners-Lee/1996/ppf.html
375 | - https://en.wikipedia.org/wiki/Usenet `x.*.**`
376 | - https://en.wikipedia.org/wiki/Namespace
377 | - https://www.postman.com/
378 | - https://www.dns.toys/
379 | - https://en.wikipedia.org/wiki/Nucleic_acid_notation
380 | - https://en.wikipedia.org/wiki/Alfred_(software)
381 | - https://github.com/ch11ng/exwm
382 | - https://github.com/dundalek/awesome-lisp-languages (`#BiwaScheme`)
383 | - https://orgmode.org/manual/Properties-and-Columns.html (`#PROPERTY:`)
384 | - https://www.openapis.org/
385 | - https://postgrest.org/en/stable/references/api/url_grammar.html
386 | - https://jqlang.github.io/jq/ (json_grammar.html)
387 | - https://en.wikipedia.org/wiki/Bookmarklet
388 | - https://platform.openai.com/docs/plugins
389 | - https://en.wikipedia.org/wiki/Sam_(text_editor)
390 | - https://en.wikipedia.org/wiki/Plan_9_from_Bell_Labs
391 | - https://plan9.io/sys/doc/acme/acme.html
392 | - https://en.wikipedia.org/wiki/Ed_(text_editor)
393 | - https://en.wikipedia.org/wiki/Bash_(Unix_shell)
394 | - https://en.wikipedia.org/wiki/Unix_filesystem
395 | - https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API
396 | - https://docs.python.org/3/glossary.html#term-argument
397 | - https://en.wikipedia.org/wiki/Placeholder
398 | - https://en.wikipedia.org/wiki/Wikipedia:Directory → https://en.wikipedia.org/wiki/Wikipedia:Directories_and_indexes
399 |
400 | Explore as well:
401 | - https://stackoverflow.com/questions/4163879/call-javascript-function-from-url-address-bar
402 | ## Notes
403 | Creating and using URI/URL, with a comprehensive syntax, allows to
404 | interact with the destination website/application, to feed it input
405 | parameters (and their values). This is a general pattern used in the
406 | Web and computing systems in general, for accessing web address and
407 | file system references.
408 |
409 | The data contained in the URL can then be re-used in the web site as
410 | an application input value, and that works well with web-components
411 | (executed on the user client side).
412 |
413 | ```txt
414 | https://example.org/my-app?my-attribute=true&my-data={"my-json": 2}
415 |
416 | ```
417 |
--------------------------------------------------------------------------------
/docs/doc-debug.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/internet4000/find/1d224cb549e11aaa760221cfa1819ef19010f3fe/docs/doc-debug.png
--------------------------------------------------------------------------------
/docs/example-queries.txt:
--------------------------------------------------------------------------------
1 | &gh internet4000 find
2 | +space hello world
3 | +data-json {"my_boolean": true}
4 |
--------------------------------------------------------------------------------
/docs/readme.md:
--------------------------------------------------------------------------------
1 | > Check the other files of this folder for more documentation.
2 |
3 | # Find
4 | Web browser URL search engine utility to customize the omnibar actions.
5 |
6 | It is built as a single importable file, without dependency, that can
7 | run in web browsers and node.js javascript contexts.
8 |
9 | It is distributed as [a
10 | website](https://internet4000.github.io/find/), [javascript
11 | class](https://github.com/internet4000/find/blob/main/src/index.js),
12 | [npm package](https://www.npmjs.com/package/i4k-find) and [git
13 | repository](https://github.com/internet4000/find).
14 |
15 | To install and use a personal/community instance, follow the
16 | installation/deployment guides.
17 |
18 | ## Browser search engine
19 |
20 | To make Find the default search engine of a web browser:
21 |
22 | 1. Visit [a find instance homepage](https://internet4000.github.io/find)
23 | 2. Follow this [wiki how
24 | guide](https://www.wikihow.com/Change-Your-Browser%27s-Default-Search-Engine)
25 | for the specific device and browser
26 |
27 | Alternatively, adding manually the search engine could be done with this open search browser config:
28 |
29 | ```
30 | Search engine: `Find`
31 | Keyword: `f`
32 | Query URL: `https://internet4000.github.io/find/#q=%s`
33 | ```
34 |
35 | 3. Make the new Find search engine the default search engine (optional,
36 | recommended).
37 | 4. Now it should be possible to use the functionalities of Find in the URL bar of the web browser
38 |
39 | > The mobile installation is not the easiest, but works on Firefox; web-browsers
40 | > are making their bread and butter on the default search engines, and our
41 | > queries; so they sometimes make changing it slightly annoying.
42 |
43 | ## Usage
44 | All find "search queries" or "commands", are to be run in the browser
45 | omnibox, or a find search input.
46 |
47 | A "find search query" is a string of text, which "Finds tries to
48 | decode", to find some syntax it knows, to build (destination) URLs
49 | (what the user is requesting).
50 |
51 | The user query string, is splitted into a list of strings, for every
52 | white space, and from there, find looks for a "symbol", probably the
53 | first character of the first string, for example `!`, or `+`.
54 |
55 | It then looks for an "engine ID", for example `m` in the user query
56 | starting with `!m`.
57 |
58 | The last part, are the user *arguments* to the the requested
59 | destination URL/web-application.
60 |
61 | For example `!m tokyo` in order to *search* (`!`) for "tokyo" on the
62 | map application (`m`).
63 |
64 | ### Symbols
65 |
66 | If the query we write in Find starts by one of these **symbols**, Find will try
67 | to decrypt the user query to see if it can do something with it.
68 |
69 | All available symbols are:
70 |
71 | - `!` = search
72 | - `+` = action
73 | - `&` = build
74 | - `#` = command (no custom engines)
75 | - if there are no symbols, the query is forwarded untouched to the default search engine
76 |
77 | Symbols are a way to give semantic meaning to engines. It should help
78 | organize what the engines do, what parameter and query they can accept.
79 |
80 | ### Engines by symbols
81 |
82 | For an up-to date list of default engines by symbols, look at the `index.js`
83 | file.
84 |
85 | All these symbols can be overwritten by the user, and new ones can be added.
86 |
87 | #### ! search
88 |
89 | These engines are stored under this `!` symbol, because they provide
90 | search results, from your query.
91 |
92 | - `!c ` - contacts.google.com
93 | - `!d ` - duckduckgo.com
94 | - `!dd ` - devdocs.io
95 | - `!dr ` - drive.google.com
96 | - `!m ` - maps.google.com
97 | - `!osm ` - openstreetmap.org
98 | - `!w ` - en.wikipedia.org
99 | - `!y ` - youtube.com
100 | - if unknown keyword - !keyword and queries fallback to default search
101 | engine, currently duckduckgo
102 | - if nokeyword - search goes to default search engine
103 |
104 | #### + action
105 |
106 | These engines are stored under this `+` symbol, because they will allow you to
107 | complete an action; add a item to a library, create a drawing, find a random
108 | image or text etc.
109 |
110 | - `+r4 [url]` - add a new track to a radio4000, from a youtube URL
111 | - `+draw [title]` - open a new drawing in Google Drive Draw
112 | - `+doc [title]` - open a new Google Docs document
113 | - `+sheet` - open a new Google Spreadsheets document
114 | - `+gmail` - open a new Gmail (Google Mail) email
115 | - `+wr` - random wikipedia article
116 | - `+wri` - random wikipedia image media
117 | - `+r4p` [radio] - play a radio4000 radio
118 | - `+r4pr` [radio] - play a random track from a radio4000 radio
119 |
120 | #### & build
121 |
122 | These engines are stored under this `&` symbol, because the parameters
123 | taken by the engines allows you to build complex URLs.
124 |
125 | - `&gh [actor] [repo]` - github/[actor]/[repo]
126 | - `&gl [actor] [repo]` - gitlab/[actor]/[repo]
127 | - `&firebase [project]` - firebase/[project]
128 | - `&netlify [project]` - netlify/[project]
129 | - `&r4 [radio]` - radio4000/[radio]
130 |
131 | #### # command
132 |
133 | This is a special symbol, for command functions within find.
134 |
135 | - `#add `
136 |
137 | adds a custom engine, by its `engine-id`, under a specific `symbol`
138 |
139 | ```
140 | #add ! gh https://github.com/search?q=
141 | ```
142 |
143 | - `#del `
144 |
145 | deletes a custom engine, by its `engine-id`, under a specific `symbol`
146 |
147 | ```
148 | #del ! gh
149 | ```
150 |
151 | ### Update default search engine
152 |
153 | It is possible to customize the default search engine used by find.
154 |
155 | We have to overwrite the engine under the id `d` (`!d`; **d** for _default_).
156 |
157 | For this we can use the following "find command", to make Google our default search engine.
158 |
159 | ```
160 | #add ! d https://encrypted.google.com/search#q={}
161 | ```
162 |
163 | To use these triggers, for exemple with the search query `foo`:
164 |
165 | - Put the cursor in the URL bar of the web-browser
166 | - Type the website's `!keyword` (the website on which you want to
167 | search. ex: `!y` for Youtube), prefixed with a `!`.
168 | - After the keyword, add a `space` (just normally as in between two
169 | words), and type our _search query_, in this exemple we said
170 | `foo`
171 | - At this point the URL bar should have this written in `!y foo` (there
172 | is a space in between `!y` and `foo`).
173 | - Press `enter` (the return key), to validate our search.
174 | - Now you should be on Youtube, with the search results for our
175 | search querry `foo`.
176 |
177 | Note: in the exemple above `Find!` is considered to be our default
178 | search engine. If it is not, and you use it as one of Firefox's "one click
179 | search engine", or Chrome/Chromium's "other search engine", you have
180 | to follow the same steps as above but as a first step you need to
181 | _trigger the search `Find!` search engine_ ("Tab" key in Firefox /
182 | "one space" in Chrome/ium, after writting the keyword).
183 |
184 | ### Add custom engines
185 |
186 | The interest of Find is the possibility to add a custom engines,
187 | and replace the default ones depending on our preferences.
188 |
189 | There are different ways to add engines (works for all symbols, but `#`):
190 |
191 | - `#add` command
192 | - `Find` object in the browser console (Try: `Find.help()`)
193 | - edit the code and host an instance
194 |
195 | ### Sync data between devices
196 |
197 | to `sync` custom engines between devices, we use a trick with the password manager, and take advantage of the user usual way to synchronise credentials between their devices.
198 |
199 | > This operation currently overwrites existing user defined engines, when
200 | > importing new ones (in does not merge them).
201 |
202 | 1. save the "application data" (user defined engines and symbols), as a JSON string, into a password manager, for this "find instance" URL
203 | 2. in the other devices, import by "login in" this site (in the "sync section"), which will request the credentials for this site (actually the application data we just saved from our device).
204 |
205 | The imported data, is written as the new user defined engines, and saved to local storage for this browser.
206 |
207 | ### `search` engine urls
208 |
209 | 1. Go to the website you would like to add and search for `foo` in the
210 | search input.
211 | 1. Wait for the search result to appear and copy the URL of the search
212 | result page, it should have `foo` in it (usually after a parameter
213 | called `q`, or `query`, but it could be a different pattern). Copy
214 | everything, from the `scheme://` to `foo` (excluded).
215 |
216 | > Note that you can also use the information stored in the `.xml` file
217 | > possibly used by websites to define their `Open Search
218 | Description`. To do that, inspect the HTML code of the site you want
219 | > to add and search for a HTML link tag with the folloing type:
220 | > `application/opensearchdescription+xml"`. The file it points to will
221 | > have the infortmation you are looking for in the `Url` XML tag.
222 |
223 | ### API(s)
224 | Find has different interfaces, some of which can be used
225 | programatically (better than others):
226 |
227 | - through its URL: [internet4000.github.io/find/#q=[query]](https://internet4000.github.io/find/#q=[query]) with a Find search query
228 | - through the `I4kFind` Javascript class exported by the package (and
229 | `.find("my query")` public method)
230 | - through the graphical interface `./src/ui/index.js`, and all
231 | exported web-components
232 | - through the `./service-worker.js` client side OpenSearch suggestions
233 | API (experimental; see development notes)
234 |
235 | ## Host a personal instance
236 | 1. deploy and host the site on a server
237 | 2. edit the file `assets/opensearch.xml` to fit the URL address of the
238 | instance
239 |
240 | ## Privacy
241 | This software does not collect any data, there are and should be no
242 | analytics functionalities on the user queries and usage.
243 |
244 | It stores in the browsers local storage (could be improved, or
245 | enhanced), only the user defined customization(s).
246 |
247 | ### (Privacy warning) Cloudflare analytics
248 |
249 | There is a cloudflare analytics beacon.
250 |
251 | It sends a HTTP get request, to cloudflare, to check if it can. If it
252 | can, it warns the user that they should install a "blocker" with
253 | instructions.
254 |
255 | If the HTTP request succeeds (user has no advert blocker),
256 | [Cloudflare](https://www.cloudflare.com/analytics/), eventually must
257 | be saving the "request information", for a certain amount of time.
258 |
259 | The user query is (and should) never be shared with Cloudflare, the
260 | `#` param where the user request, always stays on the client side of
261 | the browser.
262 |
263 | It is used to warn the user:
264 | - if the request goes through to cloudflare, that they should install
265 | a advert-blocker. The resulting analytics of user who do not have
266 | advertising de-activated, are stored in Cloudflare analytics, but will
267 | never be used to process user data of any kind. Sometimes an admin
268 | looks at the map to see where the request to the site comes from.
269 | - if the request is rejected, it removes itself from the DOM (see
270 | @TODO:flag-rm-analytics-beacon)
271 |
272 | ### About the hash parameter
273 | When making a search to an instance of find, the user query is passed
274 | to the client side application, and never to the server.
275 |
276 | The query should never leave the user browser (and reach the server
277 | hosting the site serving the Find webpage and code), [as it is passed
278 | to the browser as value of the `hash` parameter](
279 | https://en.wikipedia.org/wiki/URI_fragment).
280 |
281 | This should help protect more the privacy of the user, as the value of
282 | the `hash` parameter in a URL, does not "leak the user query" to the
283 | server it is hosted on (or any third party; there are none, except the
284 | Cloudflare beacon, which can be removed; @TODO: add flag to local
285 | storage to not even insert; but need to define first user settings,
286 | more than just the custom engines).
287 |
288 | - Find uses the [hash](https://en.wikipedia.org/wiki/URI_fragment) `#`
289 | URL Search Parameter; uses `#q=`
290 | - versus the [query](https://en.wikipedia.org/wiki/Query_string) `?`
291 | URL Search Parameter (do not use; it used to only handle `?q=`, but
292 | removed for the reason explained here; @TODO:rm-query-search-param
293 | currently left in as fallback for legacy migration; and maybe
294 | alternative entry point, somehow if some need)
295 |
296 | ## Debug this software (live, in the browser)
297 | The easieset way to start debugging is from the developer tools of
298 | a web browser. Because Find is unminified javascript code, it is
299 | possible to look at what read what the code does and where it
300 | fails. You can for example use a debugger to follow how a query is
301 | translated.
302 |
303 | From a browser we can look at it like so:
304 |
305 | .
306 |
307 | ## Firefox notes
308 |
309 | In firefox omnibar, we can use the prefixes:
310 |
311 | ```text
312 | * to search for matches in bookmarks
313 | % to search for matches in currently open tabs
314 | ^ to search for matches in browsing history
315 | > to search for marches in firefox actions
316 | + to search for matches in tagged pages
317 | # to search for matches in page titles
318 | $ to search for matches in web addresses (URLs)
319 | ? to search for matches in suggestions
320 | ```
321 |
--------------------------------------------------------------------------------
/docs/security.md:
--------------------------------------------------------------------------------
1 | # Security
2 | This document should (tries to) describe the security model followed
3 | by Find; what should make it privacy friendly, how a user query is
4 | kept private, and only shared with the destination site.
5 |
6 | ## Contact
7 | Please get in touch over the matrix chat if you have any security
8 | concerns.
9 |
10 | ## Disclaimer(s)
11 | Naturally, one needs to trust all the destinations site in the list,
12 | and the people choosing them.
13 |
14 | There is the possibility that a user "misstypes a search", calling "an
15 | other engine and symbol than expected"; which will result in sharing
16 | the query with the destination URL.
17 |
18 | I don't think this is a security risk, but a concern to be sure "what
19 | we're typing", and what it is doing (also what is the sensitivity of
20 | the user query).
21 |
22 | > Also, there lack tests.
23 |
24 | ## Model
25 | Listing the different areas encompassed by the threat modeling.
26 |
27 | > If some areas are missing, we need to implement them.
28 |
29 | ### Software
30 | - the software is open and free, and can be customized by the users
31 | - logic implemented in a single "small" vanilla javascript file
32 | - the UI is implemented in more files (loaded if the query does not
33 | result in a URL to open)
34 | - there is no "build step" to execute the code
35 | - there are no dependencies at build and run time (but a web-browser)
36 | - does not store or share user data (other than the user
37 | customization, if any)
38 | - allows export and import of the user configuration as JSON data
39 |
40 | ### Infrastructure
41 | - the software is shared on git://github.com/internet4000/find.git
42 | - the demo/"main" instance is hosted on github pages
43 | - the pages are deployed from an action "recipe" workflow
44 | - serveral recipes are shared for user to deploy their own instance
45 | - new github tags deploy a new version of the package to the public
46 | npm registry (matches the `package.json.version` number)
47 | - user can and are invited to run their own instance
48 | - running a personal instance should be made accessible, maybe 1-click
49 |
50 | It should be possible to:
51 | - distribute the code from a (machine) local server or a
52 | personal server behind a VPN
53 | - make it a browser extension to have the code separated from "the
54 | real internet", if a user wants
55 | - distribute the code on a "random" or tempory URL, such as an embed
56 | javascript bookmarklet or a "decentralized storage"
57 |
58 | ### Distribution
59 | As Javasript (Class, web-components, node.js scripts), HTML, CSS
60 | code:
61 | - main instance demo site https://internet4000.github.io/find
62 | - npm package https://www.npmjs.com/package/i4k-find
63 | - git repository https://github.com/internet4000/find
64 |
65 | ### Query to Find
66 | - is never shared to other sites or third parties
67 | - is typed in the browser URL address-bar/omnibox, and passed to Find
68 | if it does not resolve in a "pattern" (URI, reserved keywords), that
69 | the browser "knows" (`view-source:`, `javascript:`, `https://**`,
70 | `ftp://` etc.)
71 | - is passed to Find, if it is registered as a _browser protocol
72 | handler_ (not yet supported)
73 | - is passed to Find, if it is used on an "instance" site, through the
74 | interface elements (search input, query builder button etc.)
75 | - is passed to Find if it is called as a Javascript module with
76 | functions
77 | - is passed to find through the URL hash `#` parameter `#q=`, and
78 | should therefore not be shared with the server hosting Find's code
79 | - can be passed to the search `?` search parameter if the user uses it
80 | (which is shared to the server, to be acknownledged when using)
81 | - is "read by find" to build a destination URL (or an other Find
82 | query), and "transformed" by replacing the user patterns
83 | - is shared with a local API endpoint
84 |
85 | ### Request from Find
86 | How Find uses the resulting URL from a Find query.
87 |
88 | #### Query resolving
89 | - Find replaces the current browser page's URL, by the URL that was
90 | resolved from a user query
91 | - the user query is embeded in this website URL, following the URL
92 | pattern for the "symbol and engine" that were requested
93 | - resolves in a URI/URL or Find query (interpreted again), and Find
94 | opens a new browser URL, expected if asked not to in
95 | `Find(query, open)`
96 | - can result in a `https:` URL proxying other protocol(s) `gopher:`
97 | - can result in a `https:` proxy being used to display, as text,
98 | unsupported for opening as URL, but usefull, protocols; such as
99 | `data:` to share data
100 |
101 | #### Local API endpoint
102 | > Currently not working when called from a browser URL box, only from
103 | > the the Find UI.
104 |
105 | - the `/api/suggestions#q=%s` local endpoint, is built in a
106 | `service-worker.js` file, served with the site, executed locally
107 | - it is used if a user uses the search UI element(s)
108 | - ff a user has browser search/URL typing suggestions enabled, the
109 | browser shares by default the typing suggestions (each character
110 | change) to the OpenSearch.xml suggestions endpoint
111 | - the Find OpenSearch description, specifies the `#` param for user
112 | queries to be passed as the `%s` OpenSearch Placeholder
113 | - currently no data is queried externaly from Find by its suggestion
114 | system (but exploring how to "forward the sugggestions" if a
115 | destination URL has support for them in their OpenSearch.xml)
116 | - suggestions only consist of Find existing symbols engines (but could
117 | soon contain "community packages suggestions"; @TODO:beware of user
118 | generated content when in place)
119 |
120 | ## Forging links
121 | Malicious actors could be forging links, that a Find user could click.
122 |
123 | ```txt
124 | https://internet4000.github.io/#q=hello
125 |
126 | ;; encodeURI('https://internet4000.github.io/#q=')
127 |
128 | https://internet4000.github.io/#& internet4000 find
129 | "https://internet4000.github.io/#&%20internet4000%20find"
130 |
131 | https://internet4000.github.io/#q=#add ! d https://test.org/threat/?q={}
132 | https://internet4000.github.io/#q=#add%20!%20d%20https://test.org/threat/?q=%7B%7D"
133 |
134 | ;; Or more generally if "pipes" and recursive Find come in
135 | #export |
136 | #export | https://test.org/threat/?q=
137 | ;; which would look like
138 | https://internet4000.github.io/#q=#export | https://test.org/threat/?q=
139 | https://internet4000.github.io/#q=#export%20%7C%20https://test.org/threat/?q=
140 | ```
141 |
142 | We should enforce methods so it does not lead to an unwanted action,
143 | such as changing the user configuration, executing aribtrary code,
144 | opening destination, or transiant URLs, not explicitely aknowledged by
145 | a user.
146 |
147 | There was a `window.confirm()` call before executing a `#` command
148 | call, but was removed. Maybe this should be enforced again, for this
149 | and other scenarios.
150 |
151 | To mitigate this risk, users could deploy their own instance, to a
152 | "private URL" (either behind a login flow), or "unshared with a random
153 | pattern" (example, deploy from private github repo with name
154 | `my-find-abcd1234` for `.github.io/my-find-abcd1234`; gitlab
155 | also has "authed private pages for free").
156 |
157 | ## Notes
158 | Get in touch for any concern, or contribution; this is experimental.
159 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Find
5 |
6 |
7 |
8 |
9 |
10 |
12 |
13 |
14 |
15 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/license.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "i4k-find",
3 | "version": "1.4.3",
4 | "description": "URL action engine",
5 | "main": "src/index.js",
6 | "type": "module",
7 | "scripts": {
8 | "dev": "serve -p 8000 || python3 -m http.server --directory .",
9 | "test": "ava",
10 | "opensearch": "node ./src/scripts/opensearch-xml.js ?generate=true",
11 | "find": "node ./src/scripts/i4k-find.js"
12 | },
13 | "bin": {
14 | "i4k-find": "./src/scripts/i4k-find.js"
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "git+https://github.com/internet4000/find.git"
19 | },
20 | "author": "internet4000 and contributors",
21 | "license": "GPL-3.0-or-later",
22 | "bugs": {
23 | "url": "https://github.com/internet4000/find/issues"
24 | },
25 | "homepage": "https://github.com/internet4000/find#readme",
26 | "devDependencies": {
27 | "ava": "^5.3.1",
28 | "serve": "^14.2.0"
29 | },
30 | "ava": {
31 | "files": ["src/tests/**/*"]
32 | },
33 | "i4k-find": {
34 | "localStorageKey": "i4find",
35 | "queryParamName": "q",
36 | "shortName": "Find",
37 | "description": "Find search",
38 | "image": "https://internet4000.github.io/find/assets/favicon.ico",
39 | "templateHTML": "https://internet4000.github.io/find/#q={searchTerms}",
40 | "templateXML": "https://internet4000.github.io/find/assets/opensearch.xml",
41 | "templateSuggestions": "https://internet4000.github.io/find/api/suggestions/#q={searchTerms}"
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Find!
2 | Find (`I4kFind`) is a privacy friendly, client side, local/URL first
3 | toolkit, to customize a web browser's URL Omnibox (the search/address
4 | bar).
5 |
6 | > There are more examples of usages, and development notes in the
7 | > [./docs](./docs/) folder.
8 |
9 | > Remember, this is an experimental project, please make regular
10 | > backups of your custom syntax, and "pin a package version that
11 | > works" if you are running a custom instance. For full privacy, run a
12 | > personal instance.
13 |
14 | It _does not need to be installed as a browser extension or addon_,
15 | though the UX feels more fluid when used as "default search engine"
16 | (can be self hosted, but does not need to in order to be customized).
17 |
18 | It does not make any search request itself, "just builds URLs" of
19 | _specialized websites_, to which is passed the user's "search query"
20 | (it could also be the value of URL parameters of any destination
21 | application).
22 |
23 | # Usage
24 |
25 | On [internet4000.github.io/find](https://internet4000.github.io/find)
26 | it is possible to make queries to Find, such as `!docs usage` which
27 | will redirect the browser page, to this document (to the link with
28 | `#usage`).
29 |
30 | How it could be used:
31 |
32 | - as fallback when the browser does resolve a URL address
33 | - "normal web search" by default (and if no Find syntax is
34 | found), to the "default web search engine"
35 | - decide with which sites and application to share a search query, by
36 | "routing them" directly to a destination site
37 | - choose _on which search engine to search_, web search (default), map
38 | position (`!m`), contacts (`!c`), wikipedia (`!w`) new spreadhseet
39 | (`+sheet`), matrix link `&mx @user:domain.tld`, create a WebRTCPeer
40 | data channel to `&rtcmx @user:domain.tld`) etc. It is all built on
41 | open standard web technologies
42 | - DuckDuckGo also supports Bangs!, which will then be used if Find
43 | does not know a "search `!` engine"; ex: `!def find` (will will
44 | delegate the to DDG, which knows what to do with `!def`)
45 | - save "user defined URLs" as engine(s) (a sort of "bookmark"), to be
46 | re-accessed from their "shortcode", `!ex` → `https://example.org`
47 | - "route" the user query (with arguments), to any website
48 | (application), by building its URL
49 | - build (custom) "destination URL" from patterns and placeholders
50 | `https://example.org/my-app/{}/?query={}` (no support for named
51 | placeholders yet)
52 | - URL utilility, build URIs, "data URL" (ex: `data:text/html,
Hello
53 | world
`), to copy/share/edit/store temporary data, in various
54 | formats
55 | - "pipe" outputs of other web-apps together, by their "(URL) outputs"
56 | - re-assign and customize the syntax, engines URLs and actions (under
57 | the exisiting symbols); so it is the "user's favorite
58 | applications/sites" that are used by default
59 | - synchronize between device(s) and browsers, without additional user
60 | account (export/import to JSON, save as "site credentials", in JSON,
61 | and optionally synchronize with the user/browser's password manager)
62 | - host a custom instance (with CI/CD or drag and drop), implemented in
63 | vanilla HTML/CSS/Javascript(web-components), with no dependency and
64 | no build-system (could be implemented with wasm or other tools)
65 | - define a new custom/local/browser-based "[open
66 | search](https://opensearch.org/)" engine
67 | - "locally self hosted", with the web interface (`git clone`, `npm i
68 | && npm run serve`, open `https://localhost?q=%s`, should be
69 | discoverable as browser "open search engine"; and could use a
70 | different "suggestion API"; or under VPN, such as a Tailscale
71 | tailnet, for all devices to share)
72 | - (experiemental) get typing _suggestions_ from a client side API
73 | (web-worker following the OpenSearchDescription suggestion
74 | specification, catching "fetch queries" made to its own domain
75 | (`window.location/api/suggestions/`))
76 | - (experiemental) "proxy/polyfill URISchemeProtocol
77 | `<:>/>`, to support a fallback when user
78 | requests `gopher://gopher.floodgap.com`,
79 | `gemini://kennedy.gemi.dev`, `finger://`, `text://` etc.
80 | - as an accessible _starting template_ to experiment with what can the
81 | browser URL can be used for, and how to _interpret_ and _execute_
82 | queries, manage user defined data, syntax, functions
83 | - an open "finder/Alfred/CLI" for the web; can be used to suggest
84 | custom prefilled links and utilities (ex: community projects
85 | `+issue` or `+chat`)
86 | - embeded in an other app/site (ex: matrix.org iframe widget)
87 | - test/explore/save other aplication(s) "URL params", connect them
88 | together, transform their output(s)
89 | - explore new URI schemes and string data de/encoding patterns
90 | - customize a user browser's starting page, default new tab, homepage,
91 | HTML input and text string encoding/decoding/evaluation
92 |
93 | For additional usages see the [documentation](./docs/) folder.
94 |
95 | # How
96 | Find is opened by the browser, as a search engine, with the query
97 | typed by the user in their web-browser's URL bar (or from a query
98 | inside a `` web-component, or a call to
99 | `Find.find("my query")` etc.).
100 |
101 | From the query, it will try to look for "the pattern it knows", to see
102 | it the user typed a Find query, if there are none, it will default to
103 | seaching, like a usual web-search, to the user's default search engine
104 | (to be defined by the user)
105 |
106 | # Help
107 | For community chat and support, see the
108 | [#i4k-find:matrix.org](https://matrix.to/#/#i4k-find:matrix.org) room,
109 | or the [git issues](https://github.com/internet4000/find/issues), as
110 | you see fit. Feedback, bug reports, engine/symbol/feature requests,
111 | suggestions welcome.
112 |
113 | For new URL patterns, syntax and engine suggestions `>i4kfpm `
114 | for searching github repo with topics:
115 | "[i4k-find+package](https://api.github.com/search/repositories?q=fork:true+topic:i4k-find+topic:package+)
116 |
117 | # Install
118 | It is possible to use Find with
119 | - the default find instance website
120 | - a personal find instance website (can customize more)
121 |
122 | ## As a browser search engine
123 | In general, the UX should feel nicer when any instance is defined as
124 | the default web browser's search engine. Otherwise it is also possible
125 | to use a browser search engine keyword (still need to install a Find
126 | instance as a search engine in the browser, but no need to defined as
127 | the default one, as long as it has a keyword, which has to be prefixed
128 | to every find query).
129 |
130 | ## As a npm package
131 | 1. use the npm package [i4k-find](https://www.npmjs.com/package/i4k-find).
132 | 1. check the `./index.html` file for how to import the package and the GUI.
133 | 1. customize the `assets/opensearch.xml` file for the new instance URL and information
134 |
135 | It should be also available through a CDN: [!cdn
136 | i4k-find](https://internet4000.github.io/find/#q=!cdn%20i4k-find) to
137 | import.
138 |
139 | # About
140 | The URL bar of web-browsers is used to write text, websites adresses
141 | and search queries. Find is a tool that offers a user the possibility
142 | to customize the functionalities of any (device) web-browser's [URL
143 | Address Bar](https://en.wikipedia.org/wiki/Address_bar) (aka the
144 | [omnibox](https://en.wiktionary.org/wiki/omnibox)).
145 |
146 | It is similar (and a lighweight, self-hostable, customizable, free
147 | software alternatieve) to [DuckDuckGo
148 | bangs](https://duckduckgo.com/bangs), and runs only in the user
149 | browser.
150 |
151 | The code is javascript running client side, and can be customized with
152 | new search engines, synchronised across devices using the native
153 | browser's password manager (treating the user search engines custom
154 | configuration as a passwrod for the instance of find you're using).
155 |
156 | It aims to be a lightweight way to enhance the URL bar, the
157 | [URI](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier)
158 | building user-experience, accesible to use and install on personal
159 | instance(s).
160 |
161 | It is Free software that can be customized and hosted quickly at your
162 | convenience.
163 |
164 | The fastest way to try its features, is by testing it with the example
165 | queries on this page: [try Find!
166 | here](https://internet4000.github.io/find).
167 |
168 | If you want to have the best experience, try it as your web browser's
169 | default search engine; so all the features are accesible directly in
170 | your URL bar (tip: focus the omnibox with the keyboard shortcut
171 | `Control + l`, the keys `Control` and the lowercase letter `L`, aka
172 | `C-l` ).
173 |
174 | ## Examples
175 | By default, a Find search query, goes to the default search engine
176 | (`!d`) in our case, [duckduckgo](https://duckduckgo.com), and it is
177 | possible to re-assign the "default search engine's value".
178 |
179 | Here are example usage of _user queries_, one can type in an input
180 | supporting _Find queries_ (such as [the one on the
181 | homepage](https://internet4000.github.io/find)). A Find search input
182 | will try to suggest the available symbols (`!&+#`) and their
183 | associated engines.
184 |
185 | > In the examples, lines prefixed with `;;` are comments, with `;;→`
186 | > outputs URL or Find queries.
187 |
188 | Example `search` with `!` symbol:
189 |
190 | ```txt
191 | ;; "default search", without anything "Find related"
192 | Hello world
193 | ;;→ https://duckduckgo.com/?q=hello+world
194 |
195 | ;; A "map" search, defaults to google map (can be re-assigned to open street map etc.)
196 | !m egypt
197 | ;;→ https://www.google.com/maps/search/egypt
198 | ```
199 |
200 | Example `build` with `&` symbol:
201 | ```
202 | ;; go to, or buid a github profile/actor url
203 | &gh
204 | ;;→ https://github.com
205 |
206 | &gh internet4000
207 | ;;→ https://github.com/internet4000
208 |
209 | &gh internet4000 find
210 | ... and more (all customizable)
211 |
212 | ;; to build a "matrix link to room/user" URL
213 | &mx #i4k-find:matrix.org
214 | ;;→ https://matrix.to/#/%23i4k-find%3Amatrix.org
215 | ```
216 |
217 | Example `do` with `+` symbol:
218 |
219 | > Type any of these in a Find search input, or in your browser URL bar
220 | > (if Find is one of your browser search engine).
221 |
222 | ```text
223 | ;; create a new google spreadsheet (with a title)
224 | +sheet my new sheet
225 |
226 | ;; draw a new "google draw"
227 | +draw hello world
228 |
229 | ;; take a note
230 | +note My note content
231 |
232 | ;; create temporary "URL space" with text/|data
233 | +space my data
234 |
235 | ;; create a "data json url" value
236 | ;; can be copied again to a new URL, stored as bookmark etc.
237 | +data-json {"my-json": true}
238 | ```
239 |
240 | Example `command` with the `#` symbol prefix (functions cannot
241 | currently be user defined, only the other exisiting symbols):
242 |
243 | ```txt
244 | ;; to "save" an engine as a new "user defined engine" (userEngines)
245 | #add ! ex https://example.org/
246 | ;;→ will save this URL, can be called as !ex
247 |
248 | ;; to add a new engine, with URL placeholders
249 | #add ! ex https://example.org/blog/{}
250 | ;;→ will save this URL, can be called as !ex
251 |
252 | ;; to add a new "buid" engine, with URL placeholders
253 | #add & ghi https://github.com/internet4000/{}
254 | ;;→ will save this URL, can be called as &ghi find (to reach the project)
255 | ```
256 |
257 | ## Why
258 | Some reasons why this project exists:
259 | - gain (self) control of where search queries go after leaving the
260 | web-browser.
261 | - to reflect on where all browser search queries and actions go (and
262 | their ammount)
263 | - experiement with what can be done from typing into any browser's URL
264 | (is the current cursor in a URL bar, a text search input, a REPL, a
265 | notebook? Or it is just me typing on the keyboard?)
266 | - experiment with maybe storing URL as bookmarks more easily; "local
267 | first/only" database explorations of "my own content" (could also
268 | optin keep track of searches, to re-use and edit, as `.bash_history`
269 | etc.)
270 | - try to handle "not just search" (alternative URL client entry point
271 | to [DDG](https://duckduckgo.com) or
272 | [Searx](https://en.wikipedia.org/wiki/Searx))
273 | - explore using the different URI/URL(s) outputed by the "user/Find
274 | search queries", by the output(s) of the "web-app/sites" they
275 | serve, and what the user is intending to do
276 | - share practical and nice URL(s) (`+wr` and `+wri` for serendipity,
277 | placeholders)
278 | - interacting with computing interface(s) (url, shell, repl, notes,
279 | chats, links) and other actors
280 |
281 | Some reasons why DuckDuckGo is the default search engine:
282 | - it supports `!` [bangs](https://duckduckgo.com/bangs) (13,563+
283 | bangs! search engines)
284 | - it seems more privacy friendly that the rest (that support bangs;
285 | are there any other?)
286 | - [SearX](https://searx.space/) instances have bangs suppport; maybe
287 | users can decide for themselves which one to use. ([ref:
288 | issue#96](https://github.com/internet4000/find/issues/96))
289 |
290 |
291 | Cons for DDG:
292 | - seems to "re-writte" the search results when you visit the search
293 | result page, again, after visiting a first result's page
294 |
295 | # License
296 | The code of this software uses the [GNU General Public License
297 | v3](https://www.gnu.org/licenses/gpl.html), which makes it [Free
298 | software](https://en.wikipedia.org/wiki/Free_software) (see
299 | `/license.txt`).
300 |
--------------------------------------------------------------------------------
/service-worker.js:
--------------------------------------------------------------------------------
1 | /* Note: not yet supported for type module ;( */
2 | /* self.importScripts("./src/index.js"); */
3 |
4 | /* The service worker is put at the root of the repo, and the site; so
5 | it has browser API access to the entire "root" of the site. */
6 |
7 | self.symbols = {};
8 | self.userSymbols = {};
9 | self.allSymbols = {};
10 | self.allEngines = [];
11 | self.pathname = "/";
12 |
13 | /* mock find/osd until we can import it */
14 | const Find = {
15 | suggestSymbols(searchQuery) {
16 | const symbol = searchQuery.slice(0, 1);
17 | const symbolData = self.allSymbols[symbol];
18 | if (symbolData) {
19 | const symbolEngines = self.allSymbols[symbol].engines;
20 | const symbolName = self.allSymbols[symbol].name;
21 | return _createSuggestions({
22 | searchQuery,
23 | symbol,
24 | symbolEngines,
25 | symbolName,
26 | });
27 | } else {
28 | return _createSuggestions({ searchQuery });
29 | }
30 | },
31 | };
32 |
33 | const _createSuggestions = ({
34 | searchQuery,
35 | symbol,
36 | symbolEngines,
37 | symbolName,
38 | }) => {
39 | /* filter for matching results */
40 | const matchingEngines = self.allEngines.filter((engineData) => {
41 | const [eSymbol, eId, eUrl, eSearch] = engineData;
42 | return eSearch.includes(searchQuery);
43 | });
44 | /* map the result to a same sized array,
45 | but open-search suggestion format */
46 | const suggestedEngines = matchingEngines.reduce(
47 | (acc, engineData) => {
48 | const [eSymbol, eId, eUrl, eSearch] = engineData;
49 | const term = `${eSymbol + eId}`;
50 | const desc = `[${eSymbol}${self.symbols[eSymbol].name}::${eUrl}]`;
51 | const newAcc = [
52 | [...acc[0], term],
53 | [...acc[1], desc],
54 | [...acc[2], eUrl],
55 | ];
56 | return newAcc;
57 | },
58 | [[], [], []]
59 | );
60 | return [searchQuery, suggestedEngines];
61 | };
62 |
63 | const _mergeSymbols = (symbols, userSymbols) => {
64 | return Object.keys(symbols).reduce((acc, currKey) => {
65 | acc[currKey] = {
66 | engines: { ...symbols[currKey].engines },
67 | };
68 | acc[currKey] = {
69 | engines: { ...acc[currKey]?.engines, ...userSymbols[currKey]?.engines },
70 | };
71 | acc[currKey].name = symbols[currKey].name;
72 | return acc;
73 | }, {});
74 | };
75 |
76 | const _mergeEngines = (allSymbols) => {
77 | return Object.keys(allSymbols).reduce((acc, symbol) => {
78 | const symbolData = allSymbols[symbol];
79 | const symbolEngines = Object.entries(symbolData.engines);
80 | const engines = [
81 | ...acc,
82 | ...symbolEngines.map(([engine, url]) => {
83 | return [symbol, engine, url, `${symbol + engine + " " + url}`];
84 | }),
85 | ];
86 | return engines;
87 | }, []);
88 | };
89 |
90 | const _handleFetch = (event) => {
91 | const url = new URL(event.request.url);
92 | const localApiUrl = self.pathname + "api";
93 | if (url.pathname === localApiUrl) {
94 | return event.respondWith(_respondWithApiRoot(event.request));
95 | } else if (url.pathname.startsWith(localApiUrl + "/suggestions")) {
96 | return event.respondWith(_respondWithSuggestions(event.request));
97 | } else {
98 | return self.fetch(event.request.url);
99 | }
100 | };
101 |
102 | const _respondWithSuggestions = (request) => {
103 | // Parse the hash query param from the request URL
104 | const url = new URL(request.url);
105 | const params = new URLSearchParams(url.hash.slice(1));
106 | const searchQuery = params.get("q");
107 | let suggestionBody;
108 | try {
109 | suggestionBody = Find.suggestSymbols(searchQuery);
110 | } catch (e) {
111 | console.info("Could not fetch any suggestion", e);
112 | }
113 |
114 | /* https://stackoverflow.com/questions/36535642/serving-an-opensearch-application-x-suggestionsjson-through-a-service-worker */
115 | return new Response(JSON.stringify(suggestionBody), {
116 | status: 200,
117 | headers: { "Content-Type": "application/x-suggestions+json" },
118 | });
119 | };
120 |
121 | const _respondWithApiRoot = (request) => {
122 | const body = {
123 | message: "Welcome to the client side Find API",
124 | suggestions: "api/sugestions#q={searchTerms}",
125 | };
126 | return new Response(JSON.stringify(body), {
127 | status: 200,
128 | headers: { "Content-Type": "application/x-suggestions+json" },
129 | });
130 | };
131 |
132 | const _handleMessage = ({ data }) => {
133 | const { symbols, userSymbols, pathname } = JSON.parse(data);
134 | /* assign the data on the worker self global object;
135 | so we can re-use these values in the suggestions */
136 | self.symbols = symbols;
137 | self.userSymbols = userSymbols;
138 | self.allSymbols = _mergeSymbols(symbols, userSymbols);
139 | self.allEngines = _mergeEngines(self.allSymbols);
140 | self.pathname = pathname;
141 | };
142 |
143 | self.addEventListener("install", (event) => {
144 | console.info("I4kFind Service Worker installed");
145 | });
146 |
147 | self.addEventListener("activate", (event) => {
148 | console.info("Service worker activated");
149 | });
150 |
151 | self.addEventListener("fetch", _handleFetch);
152 |
153 | self.addEventListener("message", _handleMessage);
154 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | /* if we are in node, polyfill what's missing to work */
2 | const isBrowser = typeof window !== "undefined";
3 | const isNode = typeof process !== "undefined";
4 | if (typeof window === "undefined") {
5 | globalThis.window = {};
6 | window.location = new URL("i4k-find://");
7 | }
8 |
9 | /* Map of default `symbols`, `engines` (their `id` and `URL`);
10 | There is the possibility of `userSymbols` with the same structure.
11 | Ideas for symbols and functions (not user defined yet):
12 | - https://www.gnu.org/software/bash/manual/bash.html
13 | - https://en.wikipedia.org/wiki/APL_syntax_and_symbols
14 | - https://en.wikipedia.org/wiki/List_of_Lisp-family_programming_languages
15 | - DDG bangs, firefox URL prefixes
16 | */
17 | export class I4kFindSymbols {
18 | get default() {
19 | return {
20 | "!": {
21 | name: "search",
22 | uri: encodeURIComponent("!"),
23 | engines: {
24 | "?": `${window.location.href}/#q=!docs%20{}`,
25 | ai: "https://chat.com/?q={}",
26 | arxiv: "https://arxiv.org/search/?query={}",
27 | docs: "https://github.com/internet4000/find/#{}",
28 | c: "https://contacts.google.com/search/{}",
29 | cdn: "https://www.jsdelivr.com/?query={}",
30 | ciu: "https://caniuse.com/#search={}",
31 | d: "https://duckduckgo.com/?q={}",
32 | dd: "https://devdocs.io/#q={}",
33 | dr: "https://drive.google.com/drive/search?q={}",
34 | eco: "https://www.ecosia.org/search?q={}",
35 | fstv: "https://firesky.tv/?filter={}",
36 | g: "https://encrypted.google.com/search?q={}",
37 | gh: "https://github.com/search?q={}",
38 | gho: "https://github.com/search?q=org:{}",
39 | ghu: "https://github.com/search?q=user:{}",
40 | ghr: "https://github.com/search?q=repo:{}",
41 | hn: "https://hn.algolia.com/?sort=byDate&query={}",
42 | k: "https://keep.google.com/?q=#search/text%3D{}",
43 | l: "https://www.linguee.com/search?query={}",
44 | libgen: "https://libgen.rs/search.php?req={}",
45 | m: "https://www.google.com/maps/search/{}",
46 | npm: "https://www.npmjs.com/search?q={}",
47 | osm: "https://www.openstreetmap.org/search?query={}",
48 | r4: "https://radio4000.com/search?search={}",
49 | sci: "https://sci-hub.se/{}",
50 | so: "https://stackoverflow.com/search?q={}",
51 | tpb: "https://thepiratebay.org/search.php?q={}",
52 | tr: "https://translate.google.com/?q={}",
53 | vinyl: "https://vinyl.internet4000.com/#gsc.q={}",
54 | w: "https://en.wikipedia.org/w/index.php?search={}",
55 | wa: "http://www.wolframalpha.com/input/?i={}",
56 | wdev: "https://developer.mozilla.org/search?q={}",
57 | whois: "https://who.is/whois-ip/ip-address/{}",
58 | y: "https://www.youtube.com/results?search_query={}",
59 | zlib: "https://z-lib.is/s?q={}",
60 | aurl: "https://web.archive.org/web/*/{}",
61 | aurlcdx: "https://web.archive.org/cdx/search/cdx?url={}",
62 | aurlid: "https://web.archive.org/web/20210311213055id_/{}",
63 | aurlis: "https://archive.is/{}",
64 | },
65 | },
66 | "+": {
67 | name: "do",
68 | uri: encodeURIComponent("+"),
69 | engines: {
70 | ai: "https://attention1.gitlab.io/ai-interface/#system={}&input={}",
71 | aurl: "https://web.archive.org/save/{}",
72 | aurlis: "https://archive.is/?url={}",
73 | draw: "https://docs.google.com/drawings/create?title={}",
74 | tldraw: "https://www.tldraw.com",
75 | /*
76 | WebBrowsers cannot directly open "data URLs",
77 | so (we will generate a goog.space with the "data URL to copy",
78 | via a new find query).
79 | ref: https://developer.mozilla.org/en-US/docs/web/http/basics_of_http/data_urls
80 | data:[][;base64],
81 | data:text/html,
82 | // how to handle the `;` for "optional param" ("named param" etc.)
83 | // should we change the placeholder from {} to [] to match URI/MDN?
84 | */
85 | data: "data:{}:{},{}",
86 | "data-plain": "data:,{}",
87 | "data-html": "data:text/html,{}",
88 | "data-json": "data:application/json;charset=utf-8,{}",
89 | /* special utilities */
90 | "data-64": "data:;base64,{}",
91 | "data-un64": "data:,{}",
92 |
93 | /* new google doc with title (no content query param;
94 | or named param for multiple strings and spaces
95 | (body, title, strings, lists etc.) */
96 | doc: "https://docs.google.com/document/create?title={}",
97 |
98 | /* A utility to go to Find the *local* development URL,
99 | since we no not store the find URL in the browser history;
100 | Also could allow access to locally executed functions.
101 | Note: ONLY "HTTP" (no -S-) URL */
102 | local: "http://localhost:3000",
103 | r4: "https://radio4000.com/add?url={}",
104 | r4p: "https://radio4000.com/{}/play",
105 | r4pr: "https://radio4000.com/{}/play/random",
106 | scanurl: "https://radar.cloudflare.com/scan?url={}",
107 | sheet: "https://docs.google.com/spreadsheets/create?title={}",
108 | space: "https://goog.space/#input={}",
109 | sqlite: "https://sqlime.org/#{}",
110 | gmail: "https://mail.google.com/mail/#inbox?compose=new&title={}",
111 | gpt: "https://chat.openai.com/?model=gpt-4",
112 | note: "https://note.internet4000.com/note?content={}",
113 |
114 | /* "pollyfill the 'view-source:' for mobile device?
115 | browser catch that first when know how to handle " */
116 | "view-source": "data:,{}",
117 | wr: "https://en.wikipedia.org/wiki/Special:Random",
118 | wri: "https://commons.wikimedia.org/wiki/Special:Random/File",
119 | wls: "https://en.wikipedia.org/wiki/Special:UrlShortener?url={}",
120 | rtc: "https://sctlib.gitlab.io/rtc/?method={}&matrix-peers={}",
121 | rtcmx:
122 | "https://sctlib.gitlab.io/rtc/?matrix-peers={}&method=matrix-user-device",
123 | webhook: "https://webhook.site",
124 | },
125 | },
126 | "&": {
127 | name: "build",
128 | uri: encodeURIComponent("&"),
129 | engines: {
130 | gh: "https://github.com/{}/{}",
131 | gl: "https://gitlab.com/{}/{}",
132 | i4kn: "https://{}.4000.network/{}",
133 | internet: "https://portal.mozz.us/{}/{}/",
134 | ipfs: "ipfs://{}",
135 | firebase: "https://console.firebase.google.com/project/{}/overview",
136 | mx: "https://matrix.to/#/{}",
137 | netlify: "https://app.netlify.com/sites/{}/overview",
138 | r4: "https://radio4000.com/{}",
139 | r4c: "https://{}.4000.radio/{}",
140 | so: "https://stackoverflow.com/questions/{}/",
141 | ytid: "https://www.youtube.com/watch?v={}",
142 | },
143 | },
144 | /* API endpoints
145 | could be used to build API calls URL patterns (postman collection style);
146 | really feels like we need a URL pattern placeholder/language improvement,
147 | for {named_pattern} {...} recursion {$} references {&id} find pattern replacement? etc. */
148 | ">": {
149 | name: "api",
150 | uri: encodeURIComponent(">"),
151 | engines: {
152 | /* github */
153 | gh: "https://api.github.com/{}",
154 | gho: "https://api.github.com//{}",
155 | ghr: "https://api.github.com/repos/{}",
156 | ghsr: "https://api.github.com/search/repositories?page=1&per_page=100&q=fork:true+{}",
157 | ghsrt:
158 | "https://api.github.com/search/repositories?page=1&per_page=100&q=fork:true+topic:{}+{}",
159 | ghu: "https://api.github.com/users/{}",
160 | ghuid: "https://api.github.com/user/{}",
161 | /* gitlab */
162 | gl: "https://docs.gitlab.com/ee/api/rest/?suggestion=add-api-json-root#note=wikip-has-txt",
163 | glg: "https://gitlab.com/api/v4/groups/{}",
164 | glsr: "https://gitlab.com/api/v4/projects?search={}",
165 | /* trying to use this value for the "I4kFind Package Manager"; a github repo search for topics */
166 | i4kfpm:
167 | "https://api.github.com/search/repositories?q=fork:true+topic:i4k-find+topic:package+{}",
168 | /* wikipedia */
169 | w: "https://en.wikipedia.org/api/rest_v1/{}",
170 | wp: "https://en.wikipedia.org/api/rest_v1/page/{}",
171 | wpt: "https://en.wikipedia.org/api/rest_v1/page/title/{}",
172 | wpm: "https://en.wikipedia.org/api/rest_v1/page/media-list/{}",
173 | },
174 | },
175 | "#": {
176 | name: "command",
177 | uri: encodeURIComponent("#"),
178 | fns: {
179 | help(app, arg) {
180 | /* Finds help URL for a user query (with symbol) or not */
181 | app.help();
182 | if (arg) {
183 | const { symbol } = app.decodeUserRequest(arg);
184 | if (symbol) {
185 | app.find(arg);
186 | } else {
187 | app.find(`!? ${arg}`);
188 | }
189 | }
190 | },
191 | add(app, arg) {
192 | /* Find function to "add a new engine":
193 | Example usage (spaces matter):
194 | #add ! ex https://example.org/?search={}
195 | */
196 | const [symbol, id, url] = arg.split(" ");
197 | if (symbol && id && url) {
198 | app.addEngine(app.getUserSymbols(), symbol, id, url);
199 | }
200 | },
201 | del(app, arg) {
202 | /* Find function to "delete an existing engine":
203 | Example usage (spaces matter):
204 | #del ! ex
205 | */
206 | let [symbol, id] = arg.split(" ");
207 | if (symbol && id) {
208 | app.delEngine(app.getUserSymbols(), symbol, id);
209 | }
210 | },
211 | export(app, arg) {
212 | /* Export userSymbols as data:json to a goog.space */
213 | const userSymbols = app.getUserSymbols();
214 | app.find(`+data-json ${JSON.stringify(userSymbols)}`);
215 | },
216 | import(app, jsonObjOrStr) {
217 | /* Import user symbols from a JSON Object or String */
218 | if (jsonObjOrStr) {
219 | app.importUserSymbols(jsonObjOrStr);
220 | }
221 | },
222 | },
223 | },
224 | /* protocol(s) "follyfill/proxy" in the form `<:>//`
225 | ref: https://en.wikipedia.org/wiki/List_of_URI_schemes
226 | For protocols, use `//` engine as the default "protocol proxy",
227 | so it is "user customizable; but kinf of private"
228 | ;; note: could lead to re-organizing symbols by protocols?
229 | ;; or it is handled by "nested Find queries in the syntax"
230 | ;; note: protocols might need "to declare Find as handler app",
231 | we should do a for each and register, somewhere
232 | */
233 | /* ex: gemini://kennedy.gemi.dev */
234 | "gemini:": {
235 | name: "gemini",
236 | uri: encodeURIComponent("gemini:"),
237 | engines: {
238 | "//": "https://portal.mozz.us/gemini/{}",
239 | // can't yet handle "protocol engine case"
240 | /* d: "gemini://kennedy.gemi.dev/{}", */
241 | },
242 | },
243 | /* ex: text://txt.textprotocol.org */
244 | "text:": {
245 | name: "text",
246 | uri: encodeURIComponent("text:"),
247 | engines: {
248 | "//": "https://portal.mozz.us/text/{}",
249 | },
250 | },
251 | /* ex: finger://thebackupbox.net/ring */
252 | "finger:": {
253 | name: "finger",
254 | uri: encodeURIComponent("finger:"),
255 | engines: {
256 | "//": "https://portal.mozz.us/finger/{}",
257 | },
258 | },
259 | /* ex: gopher://gopher.floodgap.com */
260 | "gopher:": {
261 | name: "gopher",
262 | uri: encodeURIComponent("gopher:"),
263 | engines: {
264 | "//": "https://portal.mozz.us/gopher/{}",
265 | },
266 | },
267 | /* ex: spartan://spartan.mozz.us */
268 | "spartan:": {
269 | name: "spartan",
270 | uri: encodeURIComponent("spartan:"),
271 | engines: {
272 | "//": "https://portal.mozz.us/spartan/{}",
273 | },
274 | },
275 | /* ex: nex://nex.nightfall.city */
276 | "nex:": {
277 | name: "nex",
278 | uri: encodeURIComponent("nex:"),
279 | engines: {
280 | "//": "https://portal.mozz.us/nex/{}",
281 | },
282 | },
283 | /* ex: maps:
284 | issue: `maps:` should have no `//` part in scheme */
285 | "maps:": {
286 | name: "maps",
287 | uri: encodeURIComponent("maps:"),
288 | engines: {
289 | "//": "https://www.openstreetmap.org/search?query={}",
290 | },
291 | },
292 | /* ex: git://github.com/user/project-name.git */
293 | "git:": {
294 | name: "git",
295 | uri: encodeURIComponent("git:"),
296 | engines: {
297 | "//": "https://{}",
298 | },
299 | },
300 |
301 | /* ex: git://github.com/user/project-name.git */
302 | "ipfs:": {
303 | name: "ipfs",
304 | uri: encodeURIComponent("ipfs:"),
305 | engines: {
306 | "//": "https://ipfs.io/ipfs/{}",
307 | },
308 | },
309 | /* https://en.wikipedia.org/wiki/Digital_object_identifier;
310 | ex: doi:// */
311 | "doi:": {
312 | name: "doi",
313 | uri: encodeURIComponent("doi:"),
314 | engines: {
315 | "//": "https://doi.org/{}",
316 | },
317 | },
318 | "did:": {
319 | name: "did",
320 | uri: encodeURIComponent("did:"),
321 | engines: {
322 | "//": "https://plc.directory/did:{}",
323 | },
324 | },
325 | };
326 | }
327 | constructor(userSymbols = {}) {
328 | if (userSymbols) {
329 | this.symbols = this.newUserSymbols(userSymbols);
330 | } else {
331 | this.symbols = this.newUserSymbols();
332 | }
333 | return this;
334 | }
335 | /* do not allow custom functions/commands (execute security risk;
336 | maybe until there is a decided URL DSL for Find),
337 | or custom symbol (community semantic on Find instance)*/
338 | newUserSymbols(initialSymbolsMap = {}) {
339 | return Object.keys(this.default)
340 | .filter((symbol) => !["#"].includes(symbol))
341 | .reduce((acc, symbol) => {
342 | acc[symbol] = {};
343 | const userSymbolData = initialSymbolsMap[symbol] || { engines: {} };
344 | const userEnginesForSymbol = userSymbolData.engines;
345 | acc[symbol].engines = {};
346 | if (userEnginesForSymbol) {
347 | if (symbol === "#" || !this.default[symbol]) {
348 | // noop
349 | } else {
350 | acc[symbol].engines = userEnginesForSymbol;
351 | }
352 | }
353 | return acc;
354 | }, {});
355 | }
356 | }
357 |
358 | /* a list of the default symbols */
359 | export const DEFAULT_SYMBOLS = new I4kFindSymbols().default;
360 |
361 | /* the logic for search engines and actions */
362 | export class I4kFind {
363 | constructor({ symbols, queryParamName, localStorageKey } = {}) {
364 | this.localStorageKey = localStorageKey || "i4find";
365 | this.queryParamName = queryParamName || "q";
366 | // default I4KSymbol map of available symbols
367 | this.symbols = symbols || new I4kFindSymbols().default;
368 | }
369 |
370 | /* add a new user engine to the list of user symbols' engines */
371 | addEngine(symbols, symbol, engineId, url) {
372 | if (this.symbols[symbol]) {
373 | symbols[symbol].engines[engineId] = url;
374 | this.setUserSymbols(symbols);
375 | } else {
376 | console.error("symbol", symbol, "does not exist in", symbols);
377 | }
378 | }
379 |
380 | // add a new user engine
381 | // to the list of user defined engines in user symbols
382 | delEngine(symbols, symbol, engineId) {
383 | const symbolExists = symbols[symbol];
384 | if (symbolExists) {
385 | delete symbols[symbol].engines[engineId];
386 | this.setUserSymbols(symbols);
387 | }
388 | }
389 |
390 | // replaces the placeholder `{}` in a url, with the query, if any
391 | // otherwise just returns the url
392 | replaceUrlPlaceholders(url, query, encode = true) {
393 | if (typeof url !== "string" || typeof query !== "string") return "";
394 | const matches = url.match(/\{\}/g) || [];
395 | if (!matches.length) return url;
396 | if (!query.length) return url.replace(/\/?\{\}\/?/g, "");
397 | if (matches.length === 1) {
398 | return url.replace("{}", encode ? encodeURIComponent(query) : query);
399 | }
400 |
401 | query = query.trim();
402 | const splitQuery = (function () {
403 | return (
404 | (query.includes("/") && query.split("/")) ||
405 | (query.includes(" ") && query.split(" ")) ||
406 | query.split()
407 | );
408 | })();
409 |
410 | matches.forEach(function (queryItem, index) {
411 | if (index >= splitQuery.length) {
412 | url = url.replace(/\/?\{\}\/?/g, "");
413 | } else {
414 | const value = splitQuery[index];
415 | url = url.replace("{}", encode ? encodeURIComponent(value) : value);
416 | }
417 | });
418 | return url;
419 | }
420 |
421 | // To get an engine url from its engine id,
422 | // also pass a list of symbols and a symbol
423 | getEngineUrl(symbols, symbol, engineId) {
424 | const symbolData = symbols[symbol];
425 | let engineUrl;
426 | if (symbol === "#") {
427 | engineUrl = symbolData.fns[engineId];
428 | } else {
429 | engineUrl = symbolData.engines[engineId];
430 | }
431 | return engineUrl;
432 | }
433 |
434 | // returns a result url string to open
435 | // default to "search for help if only a symbol"
436 | // idea: https://en.wikipedia.org/wiki/Interpreter_(computing)
437 | buildEngineResultUrl(
438 | userQuery,
439 | symbols = this.symbols,
440 | symbol = "!", // "search" by default
441 | engineId = "d", // on the "default" engine
442 | encode = true, // encodeUriComponent (not for "protocol:" symbol)
443 | ) {
444 | const engineUrl = this.getEngineUrl(symbols, symbol, engineId);
445 | return this.replaceUrlPlaceholders(engineUrl, userQuery, encode);
446 | }
447 |
448 | // is there a symbol in this symbol group? `!ex` returns `!`
449 | checkForSymbol(symbolGroup) {
450 | const availableSymbols = Object.keys(this.symbols);
451 | let symbol;
452 | try {
453 | // if is a URI scheme
454 | const symbolUri = new URL(symbolGroup);
455 | symbol = symbolUri.protocol;
456 | } catch (e) {
457 | // not an error
458 | }
459 | if (!symbol) {
460 | // otherwise it is "the first char", (of the symbol/engine group)
461 | symbol = symbolGroup.charAt(0);
462 | }
463 | return availableSymbols.indexOf(symbol) >= 0 ? symbol : false;
464 | }
465 |
466 | checkForEngine(symbolGroup, symbol) {
467 | if (!symbol) {
468 | return;
469 | }
470 | const engine = symbolGroup.split(symbol)[1];
471 | /* handle a symbol that is a URI scheme protocol polyfill */
472 | if (symbol.endsWith(":")) {
473 | if (engine.startsWith("//")) {
474 | /* use the "double slash as proxy engine", prefix of the "authority" */
475 | return "//";
476 | } else {
477 | /* use the "symbol as proxy engine"? or use "//" also? */
478 | return "//";
479 | }
480 | } else {
481 | return engine;
482 | }
483 | }
484 |
485 | /* in a list of symbolsMap,
486 | is an engine available (priorize first symbolsMap, the user's)*/
487 | getSymbolsMapForEngine(symbolMaps, symbol, engineId) {
488 | if (!symbolMaps.length) return false;
489 | const filteredGroups = symbolMaps.filter(function (symbols) {
490 | if (!symbols || !symbols[symbol]) return false;
491 | const { engines, fns } = symbols[symbol];
492 | if (engines) {
493 | return engines[engineId] ? true : false;
494 | }
495 | if (fns) {
496 | return fns[engineId] ? true : false;
497 | }
498 |
499 | return false;
500 | });
501 | if (!filteredGroups.length) return false;
502 | return filteredGroups[0];
503 | }
504 |
505 | // param:
506 | // - userQuery: string `!m new york city`
507 | // return:
508 | // - url: string to be openned by the browser
509 | // idea: https://en.wikipedia.org/wiki/Lexical_analysis
510 | decodeUserRequest(userRequest) {
511 | if (!userRequest) {
512 | return false;
513 | }
514 | const allSymbolMaps = [this.getUserSymbols(), this.symbols];
515 | const tokens = userRequest.split(" "),
516 | symbolGroup = tokens[0],
517 | symbol = this.checkForSymbol(symbolGroup),
518 | engineId = this.checkForEngine(symbolGroup, symbol),
519 | userRequestWithoutSymbol = symbol
520 | ? tokens.splice(1, tokens.length).join(" ")
521 | : userRequest;
522 | const decodedRequest = {
523 | tokens,
524 | symbolGroup,
525 | symbol,
526 | engineId,
527 | userRequest,
528 | userRequestWithoutSymbol,
529 | result: null,
530 | };
531 |
532 | // is the engine referenced in the userSymbols or symbols
533 | const symbolsMapWithEngine = this.getSymbolsMapForEngine(
534 | allSymbolMaps,
535 | symbol,
536 | engineId,
537 | );
538 |
539 | // if there is no symbol, the whole userRequest is the query
540 | if (!symbol) {
541 | decodedRequest.result = this.buildEngineResultUrl(userRequest);
542 | }
543 |
544 | // if there are no symbolsMapWithEngine, we don't know the engine
545 | if (!decodedRequest.result && !symbolsMapWithEngine) {
546 | decodedRequest.result = this.buildEngineResultUrl(userRequest);
547 | }
548 |
549 | // if we know the symbol and engine
550 | if (!decodedRequest.result) {
551 | /* if the symbol is a URI "protocol" */
552 | if (symbol.endsWith(":")) {
553 | /* if it is a URI from this protocol (not a "search text query"),
554 | build a result from the entire query (URI),
555 | using `//` as "protocol proxy engine ID" (of ) */
556 | const encodeUserRequest = false;
557 | if (symbolGroup.startsWith(`${symbol}${engineId}`)) {
558 | /* do not encode the URI component (broken `/` for protocol ressource pathes) */
559 | decodedRequest.result = this.buildEngineResultUrl(
560 | symbolGroup.split(`${symbol}${engineId}`)[1],
561 | symbolsMapWithEngine,
562 | symbol,
563 | engineId,
564 | encodeUserRequest,
565 | );
566 | } else {
567 | /* if there is not ["//" authority] part in the protocol scheme */
568 | decodedRequest.result = this.buildEngineResultUrl(
569 | symbolGroup.split(`${symbol}`)[1],
570 | symbolsMapWithEngine,
571 | symbol,
572 | engineId,
573 | encodeUserRequest,
574 | );
575 | }
576 | } else if (symbol === "#") {
577 | /* if the symbol is for a find "#command" */
578 | decodedRequest.result = userRequestWithoutSymbol;
579 | } else {
580 | /* for all other cases of symbols: user user request without symbol
581 | and, only encode the user query if not ">" API symbol (probably a PATH,
582 | and if not a path a multiple word, user can use "quotes''" to escape the query) */
583 | const encodeUserRequest = symbol !== ">";
584 | decodedRequest.result = this.buildEngineResultUrl(
585 | userRequestWithoutSymbol,
586 | symbolsMapWithEngine,
587 | symbol,
588 | engineId,
589 | encodeUserRequest,
590 | );
591 | }
592 | }
593 | return decodedRequest;
594 | }
595 |
596 | // check whether URL starts with a scheme
597 | checkUrl(url) {
598 | return url.startsWith("//") || url.includes("://");
599 | }
600 |
601 | openUrl(url) {
602 | // replace history state
603 | // so after transition, clicking the back button does not hit find/?q=search
604 | // that would transition again to a search result
605 | if (!url) return;
606 | if (!this.checkUrl(url)) {
607 | url = "//" + url;
608 | }
609 |
610 | /* when in browser */
611 | if (isBrowser) {
612 | window.location.replace(url);
613 | } else if (isNode && process.env.BROWSER) {
614 | // noop
615 | }
616 | return url;
617 | }
618 |
619 | // takes a string, request query of a user, decode the request
620 | // and open the "correct destination site" with the user requested query
621 | // we want that all request succeed in opening a resulting website
622 | // (AND?/OR) interpret the result with an other find action/query
623 | // idea: https://en.wikipedia.org/wiki/GNU_Readline
624 | find(request, openInBrowser = true) {
625 | if (!request || typeof request !== "string") {
626 | return;
627 | }
628 | const decodedRequest = this.decodeUserRequest(request);
629 | const { result } = decodedRequest;
630 | const { open, display, exec, find } = this.findUserAction(
631 | decodedRequest,
632 | openInBrowser,
633 | );
634 |
635 | /* depending on the requested user/symbol(consequence) action,
636 | decide of an action to "evaluate" (open,find,display,tbd...); */
637 | if (find) {
638 | this.find(result);
639 | } else if (open) {
640 | this.openUrl(result);
641 | } else if (display) {
642 | /* we will display in the "+space" symbol engine,
643 | (encodeURIComponent result?);
644 | maybe make a more general rule here; for "recursive Find" calls;
645 | query that translate to other queries, instead of "just URLs" */
646 | this.find(`+space ${result}`);
647 | } else if (exec) {
648 | this.execUserRequest(decodedRequest);
649 | }
650 | return result;
651 | }
652 | execUserRequest(decodedRequest) {
653 | const { symbol, engineId, result } = decodedRequest;
654 | const fns = this.symbols[symbol].fns[engineId];
655 | fns(this, result);
656 | }
657 | findUserAction(decodedRequest, openInBrowser) {
658 | const action = {
659 | display: false,
660 | open: false,
661 | exec: false, // user defined `#` functions
662 | find: false, // recursive call to find again
663 | };
664 | /* try the result for find syntax; URI scheme */
665 | try {
666 | const { protocol } = new URL(decodedRequest.result);
667 | if (protocol && this.symbols[protocol]) {
668 | action.find = true;
669 | }
670 | } catch (e) {
671 | // not-an-error
672 | }
673 | /* treat the special cases, which should probably not "open a tab"
674 | because "re-read as a user-query" */
675 | if (decodedRequest.symbol === "+") {
676 | // for all "do" action, which results in "data:" (a URI for no website)
677 | if (decodedRequest.result.startsWith("data:")) {
678 | action.display = true;
679 | }
680 | }
681 | /* exec (user defined) functions */
682 | if (decodedRequest.symbol === "#") {
683 | action.exec = true;
684 | }
685 | /* by default we want to open a browser window/tab, if no "display|exec|..." requested */
686 | if (openInBrowser && !action.display && !action.exec) {
687 | action.open = true;
688 | }
689 | return action;
690 | }
691 |
692 | // params: none
693 | // URL-hash-params: `q` the user query as a string we will decode
694 | // idea: https://en.wikipedia.org/wiki/Init
695 | init() {
696 | /* do-not extract user query/search from window url query param,
697 | the value of the query parameters (are HTTP sent to the server)
698 | const query = url.searchParams.get('q');
699 | use hash-param, fragment identifier instead (data not sent to server)
700 | */
701 | // take the current browser's full url
702 | const params = new URLSearchParams(window.location.hash.slice(1));
703 | const query = params.get(this.queryParamName);
704 | // if there is a value in `#` URL hash, let's "find" it
705 | let result;
706 | if (query) {
707 | result = this.find(query);
708 | } else {
709 | /* else fallback to query param for legacy */
710 | const url = new URL(window.location.href);
711 | const queryParamVal = url.searchParams.get(this.queryParamName);
712 | if (queryParamVal) {
713 | result = this.find(queryParamVal);
714 | } else {
715 | // "No search in the 'q' query parameter", noop (yet)
716 | }
717 | }
718 | return result;
719 | }
720 |
721 | // get the user symbols from local storage
722 | // or returns an empty new set of symbols
723 | getUserSymbols() {
724 | let userSymbols = {};
725 | try {
726 | userSymbols = JSON.parse(localStorage.getItem(this.localStorageKey));
727 | } catch (e) {
728 | if (e.name === "SyntaxError") {
729 | userSymbols = null;
730 | }
731 | }
732 | if (!userSymbols) {
733 | userSymbols = this.newUserSymbols();
734 | }
735 | return userSymbols;
736 | }
737 |
738 | // saves a new set of user symbols to local storage
739 | setUserSymbols(sourceSymbols) {
740 | if (!sourceSymbols) return;
741 | const serializedSymbols = this.newUserSymbols(sourceSymbols);
742 | const symbolsString = JSON.stringify(serializedSymbols);
743 | localStorage.setItem(this.localStorageKey, symbolsString);
744 | // cannot send event from here; we might be in browser||node.js
745 | }
746 |
747 | // generates new userSymbols from copying original symbols
748 | // to be used with Find default symbols (Find.symbols)
749 | importUserSymbols(sourceSymbolsJSONAny) {
750 | let userSymbols = null;
751 | if (typeof sourceSymbolsJSONAny === "string") {
752 | try {
753 | const sData = JSON.parse(sourceSymbolsJSONAny);
754 | userSymbols = sData;
755 | } catch (e) {}
756 | } else if (typeof sourceSymbolsJSONAny === "object") {
757 | userSymbols = sourceSymbolsJSONAny;
758 | }
759 | if (userSymbols) {
760 | /* "an entire object" */
761 | if (userSymbols.userSymbols) {
762 | this.setUserSymbols(this.newUserSymbols(userSymbols.userSymbols));
763 | } else {
764 | this.setUserSymbols(this.newUserSymbols(userSymbols));
765 | }
766 | }
767 | }
768 | newUserSymbols(initialSymbols) {
769 | return new I4kFindSymbols(initialSymbols).symbols;
770 | }
771 | }
772 |
773 | const App = new I4kFind();
774 |
775 | /* let's register a service worker,
776 | to try work with the open-search suggestions api, on client side only */
777 | if (isBrowser) {
778 | if ("serviceWorker" in navigator) {
779 | window.addEventListener("load", async () => {
780 | try {
781 | const moduleUrlPaths = import.meta.url.split("/");
782 | const moduleUrl = moduleUrlPaths
783 | .slice(0, moduleUrlPaths.length - 2)
784 | .join("/");
785 | /* we locate the file at the root of the project,
786 | to have a "large scope for catching fetch requests" */
787 | const sw = await navigator.serviceWorker.register(
788 | `${moduleUrl}/service-worker.js`,
789 | );
790 | if (sw.active) {
791 | /* we can't pass the entire app */
792 | sw.active.postMessage(
793 | JSON.stringify({
794 | userSymbols: App.getUserSymbols(),
795 | symbols: App.symbols,
796 | pathname: window.location.pathname,
797 | }),
798 | );
799 | }
800 | } catch (e) {
801 | console.info("Could not register service worker", e);
802 | }
803 | });
804 | }
805 | }
806 |
807 | export default App;
808 |
--------------------------------------------------------------------------------
/src/open-search.js:
--------------------------------------------------------------------------------
1 | export const DEFAULT_OSD = {
2 | shortName: "Find",
3 | description: "Find search",
4 | image: "https://example.org/i4k-find/assets/favicon.ico",
5 | templateHTML: "https://example.org/i4k-find/#q={searchTerms}",
6 | templateXML: "https://example.org/i4k-find/assets/opensearch.xml",
7 | templateSuggestions: "https://example.org/i4k-find/api/suggestions/#q={searchTerms}",
8 | };
9 |
10 | /* generate the OSD needed to register as a browser search engine */
11 | export class OpenSearchDescription {
12 | get attributes() {
13 | return [
14 | "shortName",
15 | "description",
16 | "templateHTML",
17 | "templateXML",
18 | "templateSuggestions",
19 | "image",
20 | ];
21 | }
22 | get config() {
23 | return this.attributes.reduce((acc, val) => {
24 | acc[val] = this[val];
25 | return acc;
26 | }, {});
27 | }
28 | constructor(config) {
29 | this.attributes.forEach((attr) => {
30 | const isSet = config.hasOwnProperty(attr);
31 | const val = isSet ? config[attr] : DEFAULT_OSD[attr];
32 | this[attr] = val;
33 | });
34 | }
35 | exportJSON() {
36 | return JSON.stringify({ ...this.config }, null, 2);
37 | }
38 | exportXML() {
39 | const config = { ...this.config };
40 | return `
41 |
42 | UTF-8
43 | ${config.shortName}
44 | ${config.description}
45 | ${config.image}
46 |
47 |
48 |
49 | `;
50 | /* ${config.templateHTML} */
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/scripts/i4k-find.js:
--------------------------------------------------------------------------------
1 | import findApp from "../index.js"
2 |
3 | /* Should handle user input when called from the shell */
4 |
5 | /* get the user query from the arguments to a Find node.js call */
6 | function queryFromArgs(args) {
7 | const userQuery = args.slice(2).join(" ");
8 | return userQuery
9 | }
10 |
11 | async function queryFromInputStream() {
12 | return new Promise((resolve, reject) => {
13 | process.stdin.resume();
14 | process.stdin.setEncoding('utf8');
15 | let userQueryStream = "";
16 | // user inputs data, or from shell stdin pipe `|` and `<` redirection
17 | process.stdin.on('data', (userQueryChunk) => {
18 | userQueryStream += userQueryChunk
19 | })
20 | // when the input is finished
21 | process.stdin.on('end', () => {
22 | resolve(userQueryStream.toString())
23 | })
24 | /* handle `C-d` user input, to stop, and handle, their stream;
25 | `C-c` which would stop, and cancel the input strean (no Find);
26 | no sure it is correctly done here */
27 | process.on('SIGINT', () => {
28 | resolve(userQueryStream.toString())
29 | });
30 | })
31 | }
32 |
33 | function i4kfind(readLineQuery) {
34 | const cleanQuery = readLineQuery.trim()
35 | let queryResult = ""
36 | if (cleanQuery) {
37 | queryResult = findApp.find(cleanQuery);
38 | }
39 | return queryResult
40 | }
41 |
42 | /* output for node, with a new line at the end */
43 | function outputResult(queryResult) {
44 | process.stdout.write(queryResult + "\n");
45 | }
46 |
47 | async function main() {
48 | if (process.argv.length > 2) {
49 | const query = queryFromArgs(process.argv)
50 | const queryResult = i4kfind(query);
51 | outputResult(queryResult);
52 | } else {
53 | /* read user stream */
54 | const query = await queryFromInputStream()
55 | const userQueryLines = query.split('\n')
56 | userQueryLines.forEach(query => {
57 | const queryResult = i4kfind(query);
58 | outputResult(queryResult);
59 | })
60 | process.exit(0);
61 | }
62 | }
63 |
64 | // initialize the script on file open (in node.js)
65 | main()
66 |
--------------------------------------------------------------------------------
/src/scripts/opensearch-xml.js:
--------------------------------------------------------------------------------
1 | import { OpenSearchDescription } from "../open-search.js";
2 | import packageJson from "../../package.json" assert { type: "json" };
3 | import fs from "fs/promises";
4 | import path from "path";
5 |
6 | const OSD_PATH = "assets/opensearch.xml";
7 | const pkgName = packageJson["name"];
8 | const config = packageJson[pkgName];
9 |
10 | const readUserPackageJson = async () => {
11 | const packageJsonPath = path.join(process.cwd(), "package.json");
12 | const data = await fs.readFile(packageJsonPath, "utf-8");
13 | let userData;
14 | try {
15 | userData = JSON.parse(data) || {};
16 | } catch (e) {
17 | console.info("Could not get user config", e);
18 | }
19 | return userData;
20 | };
21 |
22 | const newUserConfig = async (baseUrl) => {
23 | const userPackageJson = await readUserPackageJson();
24 | const userPkgConfig = userPackageJson[pkgName];
25 | const userConfig = { ...userPkgConfig };
26 | if (baseUrl) {
27 | try {
28 | new URL(baseUrl);
29 | const { queryParamName } = userConfig;
30 | userConfig.templateHTML = `${baseUrl}/#${queryParamName}={searchTerms}`;
31 | userConfig.templateXML = `${baseUrl}/${OSD_PATH}`;
32 | userConfig.templateSuggestions = `${baseUrl}/api/suggestions/#${queryParamName}={searchTerms}`;
33 | userConfig.image = `${baseUrl}/assets/favicon.ico`;
34 | } catch (e) {
35 | throw e;
36 | }
37 | }
38 | return userConfig;
39 | };
40 |
41 | const openSearchXml = async () => {
42 | const argumementsUrlHash = process.argv[2];
43 | let userArgs;
44 | try {
45 | userArgs = Object.fromEntries(new URLSearchParams(argumementsUrlHash));
46 | } catch (e) {}
47 | const { generate = false } = userArgs;
48 | const { I4K_FIND_URL } = process.env;
49 |
50 | if (!I4K_FIND_URL) {
51 | return;
52 | }
53 |
54 | let osdXml;
55 | try {
56 | const newConfig = await newUserConfig(I4K_FIND_URL);
57 | const osd = new OpenSearchDescription(newConfig);
58 | osdXml = osd.exportXML();
59 | } catch (e) {
60 | console.error(e);
61 | return;
62 | }
63 |
64 | if (osdXml && generate) {
65 | try {
66 | const localPath = path.join(process.cwd(), OSD_PATH);
67 | await fs.writeFile(localPath, osdXml);
68 | } catch (e) {
69 | throw e;
70 | }
71 | }
72 | return osdXml;
73 | };
74 | openSearchXml();
75 |
76 | export default openSearchXml;
77 |
--------------------------------------------------------------------------------
/src/styles/index.css:
--------------------------------------------------------------------------------
1 | /* box sizing */
2 | html {
3 | box-sizing: border-box;
4 | }
5 | *,
6 | *:before,
7 | *:after {
8 | box-sizing: inherit;
9 | }
10 |
11 | /* variables */
12 | :root {
13 | --size-font: 17px;
14 | --size: 1.5rem;
15 | --size-border: 0.2rem;
16 | --size-container: 40rem;
17 | --font-family: monospace;
18 |
19 | --c-bg: transparent;
20 | --c-bg--random: inherit; /* set by js */
21 | --c-bg--contrast: cyan;
22 | --c-bg--tonique: magenta;
23 | --c-bg--warning: white;
24 | --c-symbol: var(--c-bg);
25 | --c-symbol--search: cyan;
26 | --c-symbol--build: yellow;
27 | --c-symbol--do: magenta;
28 | --c-symbol--command: orange;
29 | }
30 |
31 | @media screen and (min-width: 70rem) {
32 | :root {
33 | --size-font: 19px;
34 | }
35 | }
36 |
37 | @media (prefers-color-scheme: dark) {
38 | :root {
39 | color-scheme: dark;
40 | --c-fg: slategray;
41 | --c-bg: transparent;
42 | --c-bg--summary: black;
43 | --c-bg--contrast: cyan;
44 | --c-bg--tonique: magenta;
45 | --c-bg--warning: white;
46 | --c-button: slategray;
47 | --c-border: slategray;
48 | }
49 | }
50 | @media (prefers-color-scheme: light) {
51 | :root {
52 | color-scheme: light;
53 | --c-fg: black;
54 | --c-bg--summary: whitesmoke;
55 | --c-button: lightgray;
56 | --c-border: lightgray;
57 | }
58 | }
59 |
60 | /* animation */
61 | @keyframes animBg {
62 | 0% {
63 | transform: scale(1) translateX(0);
64 | }
65 | 30% {
66 | transform: scale(0.1) translateX(-100%);
67 | }
68 | 70% {
69 | transform: scale(1.5) translateX(100%);
70 | }
71 | 90% {
72 | transform: scale(1) translateX(-50%);
73 | }
74 | 100% {
75 | transform: scale(1) translateX(0);
76 | }
77 | }
78 |
79 | @keyframes animLetter {
80 | 0% {
81 | opacity: 0;
82 | }
83 | 50% {
84 | opacity: 1;
85 | }
86 | 100% {
87 | opacity: 0;
88 | }
89 | }
90 |
91 | @keyframes animBang {
92 | 0% {
93 | content: "!";
94 | fill: initial;
95 | }
96 | 30% {
97 | content: "?";
98 | fill: var(--c-bg--contrast);
99 | }
100 | 60% {
101 | content: "+";
102 | fill: var(--c-bg--random);
103 | }
104 | 100% {
105 | content: "#";
106 | fill: var(--c-fg);
107 | }
108 | }
109 |
110 | /*
111 | General styles
112 | */
113 | html,
114 | body {
115 | display: flex;
116 | flex-direction: column;
117 | justify-content: center;
118 | align-items: center;
119 | }
120 | html {
121 | color: var(--c-fg);
122 | font-size: var(--size-font);
123 | font-family: var(--font-family);
124 | min-height: 100%;
125 | }
126 |
127 | body {
128 | margin: 0;
129 | background-color: var(--c-bg);
130 | }
131 |
132 | i4k-find-app input,
133 | i4k-find-app textarea,
134 | i4k-find-app button,
135 | i4k-find-app [contenteditable] {
136 | border-color: var(--c-border);
137 | border-size: var(--size-border);
138 | }
139 | i4k-find-app button {
140 | padding: 0.4rem;
141 | color: var(--c-fg);
142 | border-color: var(--c-button);
143 | cursor: pointer;
144 | border-radius: 0.2rem;
145 | border-color:;
146 | }
147 | i4k-find-app input,
148 | i4k-find-app textarea {
149 | padding: calc(var(--size) / 2);
150 | border-radius: 0.2rem;
151 | }
152 | i4k-find-app input {
153 | width: 100%;
154 | }
155 | i4k-find-app textarea {
156 | width: auto;
157 | }
158 |
159 | i4k-find-app li {
160 | margin-bottom: 0.7rem;
161 | }
162 |
163 | /*
164 | Application concerns
165 | */
166 |
167 | .App {
168 | display: flex;
169 | flex-direction: column;
170 | align-items: center;
171 | justify-content: center;
172 | padding: calc(var(--size) / 2);
173 |
174 | /* transition */
175 | transition: background-color 700ms ease-in-out;
176 | }
177 |
178 | .App-header {
179 | opacity: 1;
180 | transition:
181 | opacity 300ms ease-in,
182 | transform 300ms cubic-bezier(0.6, -0.13, 0.45, 1.06);
183 | transform: translateY(0);
184 | }
185 | @media screen (min-width: 20rem) {
186 | .App-header {
187 | flex-direction: column;
188 | }
189 | }
190 |
191 | .App-queries {
192 | padding: 0.5rem;
193 | }
194 | .App-queries menu {
195 | display: flex;
196 | flex-wrap: wrap;
197 | list-style: none;
198 | justify-content: center;
199 | align-items: center;
200 | margin: 0;
201 | padding: 0;
202 | }
203 | .App-queries menu li {
204 | margin: 0.5rem;
205 | }
206 | /* search queries in the app's list, for intro text */
207 | .App-queries menu li:first-child i4k-find-query::before {
208 | content: "⇢ Find";
209 | margin-right: calc(var(--size) / 3);
210 | }
211 | .App-queries menu li:first-child i4k-find-query button {
212 | background-color: var(--c-bg--contrast);
213 | }
214 | .App-header {
215 | display: flex;
216 | justify-content: center;
217 | align-items: center;
218 | position: sticky;
219 | top: 0.3rem;
220 | z-index: 1;
221 | }
222 | .App-header::after {
223 | content: "";
224 | z-index: -1;
225 | position: absolute;
226 | left: 0;
227 | right: 0;
228 | bottom: 0;
229 | top: 0;
230 | background-color: var(--c-bg--random);
231 | opacity: 0.8;
232 | border-radius: 0.2rem;
233 | }
234 |
235 | .App-body {
236 | opacity: 1;
237 | transition: opacity 200ms 300ms ease-out;
238 | width: 100%;
239 | max-width: var(--size-container);
240 | display: flex;
241 | align-items: center;
242 | flex-direction: column;
243 | }
244 | .Title {
245 | margin-top: 0;
246 | position: relative;
247 | text-decoration: none;
248 | font-size: 2rem;
249 |
250 | /* vertical align the image */
251 | display: flex;
252 | }
253 | .Title img {
254 | width: 7rem;
255 | }
256 | .Title h1 {
257 | display: none;
258 | }
259 |
260 | /* the search */
261 | i4k-find-search {
262 | }
263 | @media screen (min-width: 20rem) {
264 | i4k-find-search form {
265 | flex-direction: column;
266 | }
267 | }
268 | i4k-find-search form {
269 | display: flex;
270 | justify-content: center;
271 | align-items: center;
272 | width: 100%;
273 | }
274 | @media screen and (min-width: 30rem) {
275 | i4k-find-search form {
276 | flex-wrap: nowrap;
277 | }
278 | }
279 |
280 | i4k-find-search form button {
281 | /* push it from input, and stay visually centered on mobile */
282 | margin: calc(var(--size) / 5);
283 | background-color: var(--c-bg--contrast);
284 | }
285 |
286 | i4k-find-search form button:active {
287 | }
288 |
289 | i4k-find-search form input {
290 | -webkit-appearance: inherit;
291 | font-size: 1.2rem;
292 | }
293 |
294 | #Customs-table {
295 | border-collapse: separate;
296 | border-spacing: 2rem 0;
297 | text-align: left;
298 | }
299 |
300 | i4k-find-search {
301 | transform: scale(1);
302 | transition: transform 200ms ease-in-out;
303 | }
304 |
305 | i4k-find-info button {
306 | cursor: pointer;
307 | }
308 | i4k-find-info details {
309 | }
310 | i4k-find-info summary {
311 | }
312 | i4k-find-info-docs {
313 | margin-bottom: 1rem;
314 | display: flex;
315 | justify-content: center;
316 | padding: 0.6rem;
317 | }
318 |
319 | i4k-symbols-list {
320 | display: flex;
321 | flex-direction: column;
322 | margin-bottom: 1rem;
323 | padding: 1rem;
324 | }
325 | i4k-symbols-list article[symbol="!"] {
326 | --c-symbol: var(--c-symbol--search);
327 | }
328 | i4k-symbols-list article[symbol="+"] {
329 | --c-symbol: var(--c-symbol--do);
330 | }
331 | i4k-symbols-list article[symbol="&"] {
332 | --c-symbol: var(--c-symbol--build);
333 | }
334 | i4k-symbols-list article[symbol="#"] {
335 | --c-symbol: var(--c-symbol--command);
336 | }
337 |
338 | i4k-symbols-list dl {
339 | border-radius: 0.2rem;
340 | font-size: 1.7rem;
341 | width: auto;
342 | display: inline-flex;
343 | position: sticky;
344 | top: 0;
345 | margin: calc(var(--size) / 3);
346 |
347 | background-color: var(--c-symbol);
348 | background-clip: content-box;
349 | -webkit-background-clip: content-box;
350 | color: var(--c-fg);
351 | }
352 | i4k-symbols-list dd {
353 | margin-left: 0;
354 | }
355 | i4k-symbols-list ul {
356 | margin-top: 0.5rem;
357 | padding: 0;
358 | list-style: none;
359 | }
360 | i4k-symbols-list li {
361 | display: flex;
362 | flex-wrap: wrap;
363 | white-space: pre-wrap;
364 | word-break: break-all;
365 | }
366 | i4k-symbols-list li em {
367 | text-align: left;
368 | flex-grow: 1;
369 | flex-shrink: 0;
370 | }
371 | i4k-symbols-list li a {
372 | text-align: right;
373 | flex-grow: 1;
374 | }
375 | i4k-symbols-list li a mark {
376 | background-color: var(--c-symbol);
377 | }
378 | i4k-symbols-list li input {
379 | background-color: transparent;
380 | border: none;
381 | padding: 0;
382 | cursor: alias;
383 | max-width: none;
384 | outline: 0;
385 | }
386 | @media screen (min-width: 20rem) {
387 | i4k-symbols-list li pre {
388 | line-height: 1.7;
389 | font-size: 1rem;
390 | }
391 | }
392 | i4k-symbols-list li pre {
393 | tab-size: 0.1rem;
394 | white-space: pre-wrap;
395 | margin: 0;
396 | width: 100%;
397 | line-height: 1.7;
398 | font-size: 0.8rem;
399 | }
400 | i4k-symbols-list article {
401 | margin-bottom: 1rem;
402 | }
403 | i4k-symbols-list li em {
404 | margin-right: 1rem;
405 | font-weight: bold;
406 | }
407 | i4k-symbols-list li a {
408 | color: var(--c-fg);
409 | text-decoration: none;
410 | }
411 |
412 | /* searched animations */
413 | i4k-find-app[searched] {
414 | /* opacity: 0; */
415 | }
416 | i4k-find-app[searched] i4k-find-info {
417 | /* opacity: 0; */
418 | /* transform: scale(0); */
419 | }
420 | i4k-find-app[searched] i4k-find-logo {
421 | /* opacity: 0; */
422 | /* transform: scale(2); */
423 | }
424 | i4k-find-app[searched] i4k-find-search {
425 | /* opacity: 0; */
426 | }
427 | i4k-find-app[searched] i4k-find-search input {
428 | /* font-size: 5vh; */
429 | /* background-color: transparent; */
430 | /* border-color: transparent; */
431 | /* outline: none; */
432 | }
433 | i4k-find-app[searched] i4k-find button {
434 | /* display: none; */
435 | }
436 |
437 | i4k-find-app {
438 | opacity: 1;
439 | /* transition: opacity 300ms ease-in-out; */
440 | }
441 | i4k-find-app i4k-find-info {
442 | display: flex;
443 | flex-direction: column;
444 | margin: 0.5rem;
445 | }
446 | i4k-find-app i4k-find-logo {
447 | opacity: 1;
448 | transition:
449 | opacity 333ms ease-in-out,
450 | transform 333ms ease-in-out;
451 | }
452 | i4k-find-app i4k-find-logo:hover svg {
453 | transform: scale(1);
454 | }
455 | i4k-find-app i4k-find-logo svg {
456 | width: calc(var(--size) * 2);
457 | height: calc(var(--size) * 2);
458 | }
459 | /* apply the animations */
460 | i4k-find-app i4k-find-logo svg rect {
461 | transform-origin: center;
462 | transform: scale(1);
463 | transition: transform 3333ms ease-in-out;
464 | animation: animBg 33.333s ease-in-out infinite;
465 | }
466 | i4k-find-app i4k-find-logo svg g[aria-label^="F"] {
467 | /* transform-origin: center; */
468 | opacity: 0;
469 | transition: transform 333ms ease-in-out;
470 | animation: animLetter 3.333s ease-in-out infinite;
471 | animation-delay: 333ms;
472 | }
473 | i4k-find-app i4k-find-logo svg g[aria-label^="!"] {
474 | /* transform-origin: center; */
475 | /* transform: scale(1); */
476 | transition: transform 333ms ease-in-out;
477 | animation: animBang 3.333s ease-in-out infinite;
478 | }
479 |
480 | /* the search itself */
481 | i4k-find-app i4k-find-search {
482 | opacity: 1;
483 | transform: scale(1);
484 | transition:
485 | opacity 600ms ease-in-out,
486 | transform 400ms ease-in-out;
487 | }
488 | i4k-find-app i4k-find-search input {
489 | transition:
490 | background-color 200ms ease-in-out,
491 | font-size 400ms ease-in-out;
492 | border-color: var(--c-symbol);
493 | }
494 | i4k-find-app i4k-find-search input[value^="!"] {
495 | --c-symbol: var(--c-symbol--search);
496 | }
497 | i4k-find-app i4k-find-search input[value^="+"] {
498 | --c-symbol: var(--c-symbol--do);
499 | }
500 | i4k-find-app i4k-find-search input[value^="&"] {
501 | --c-symbol: var(--c-symbol--build);
502 | }
503 | i4k-find-app i4k-find-search input[value^="#"] {
504 | --c-symbol: var(--c-symbol--command);
505 | }
506 | i4k-find-app details[open] {
507 | border: none;
508 | background-color: var(--c-bg--summary);
509 | }
510 | i4k-find-app details[open] summary {
511 | margin: 0rem calc(var(--size) * 2);
512 | font-weight: bold;
513 | }
514 | i4k-find-app summary {
515 | cursor: pointer;
516 | padding: 0.4rem;
517 | text-align: center;
518 | background-color: var(--c-bg--summary);
519 | border-radius: 0.2rem;
520 | margin: 0.3rem;
521 | }
522 |
523 | /* sync */
524 | i4k-find-sync {
525 | padding: 1rem;
526 | display: flex;
527 | flex-direction: column;
528 | align-items: center;
529 | }
530 | i4k-find-sync form {
531 | display: flex;
532 | flex-direction: column;
533 | /* align-items: center; */
534 | /* justify-content: center; */
535 | }
536 | i4k-find-sync form input {
537 | flex-basis: 50%;
538 | /* display: none; */
539 | }
540 | i4k-find-sync form fieldset {
541 | margin-bottom: calc(var(--size) / 2);
542 | display: flex;
543 | flex-direction: column;
544 | }
545 | i4k-find-sync pre {
546 | white-space: pre-wrap;
547 | }
548 | i4k-find-sync textarea {
549 | flex-grow: 1;
550 | min-height: calc(var(--size) * 3);
551 | resize: vertical;
552 | }
553 |
554 | /* find query component */
555 | i4k-find-query[q^="!"] button::first-letter,
556 | i4k-find-query[q^="&"] button::first-letter,
557 | i4k-find-query[q^="+"] button::first-letter,
558 | i4k-find-query[q^="#"] button::first-letter {
559 | /* not matching correcly "&" and "!" and "#"; "+" is matched */
560 | text-decoration: underline;
561 | text-underline-position: under;
562 | text-underline-offset: 2px;
563 | text-underline-color: var(--c-symbol);
564 | }
565 | i4k-find-query[q^="!"] button,
566 | i4k-find-query[q^="&"] button,
567 | i4k-find-query[q^="+"] button,
568 | i4k-find-query[q^="#"] button {
569 | border-color: var(--c-symbol);
570 | }
571 | i4k-find-query[q^="!"] {
572 | --c-symbol: var(--c-symbol--search);
573 | }
574 | i4k-find-query[q^="+"] {
575 | --c-symbol: var(--c-symbol--do);
576 | }
577 | i4k-find-query[q^="&"] {
578 | --c-symbol: var(--c-symbol--build);
579 | }
580 | i4k-find-query[q^="#"] {
581 | --c-symbol: var(--c-symbol--command);
582 | }
583 |
584 | /* analytics */
585 | i4k-find-analytics {
586 | display: flex;
587 | padding: 1rem;
588 | margin-top: 1rem;
589 | background-color: var(--c-bg--warning);
590 | }
591 |
--------------------------------------------------------------------------------
/src/tests/index.js:
--------------------------------------------------------------------------------
1 | import test from "ava";
2 | import Find, { I4kFindSymbols } from "../../src/index.js";
3 |
4 | const DEFAULT_SYMBOLS = new I4kFindSymbols().default
5 |
6 | if (!globalThis.localStorage) {
7 | globalThis.localStorage = {
8 | getItem(key) {
9 | return this.storage[key];
10 | },
11 | setItem(key, val) {
12 | this.storage = { ...this.storage, [key]: val };
13 | },
14 | storage: {},
15 | };
16 | }
17 |
18 | // cleanup initial possible values from URL
19 | test.afterEach(() => {
20 | window.location = new URL("i4k-find://");
21 | });
22 |
23 | test("find has initial symbols", (t) => {
24 | t.like(DEFAULT_SYMBOLS["!"], Find.symbols["!"]);
25 | t.like(DEFAULT_SYMBOLS["+"], Find.symbols["+"]);
26 | t.like(DEFAULT_SYMBOLS["&"], Find.symbols["&"]);
27 | });
28 |
29 | test("find has initial command symbol with dns", (t) => {
30 | Object.entries(DEFAULT_SYMBOLS["#"].fns).forEach(([fnId, fnDef]) => {
31 | t.truthy(Find.symbols["#"].fns[fnId])
32 | t.is(
33 | DEFAULT_SYMBOLS["#"].fns[fnId].toString(),
34 | Find.symbols["#"].fns[fnId].toString()
35 | )
36 | })
37 | });
38 |
39 | test("Find.find() only works if with a string argument", (t) => {
40 | t.falsy(Find.find());
41 | t.falsy(Find.find(""));
42 | t.is(Find.find("foo"), "https://duckduckgo.com/?q=foo");
43 | });
44 |
45 | test("find builds correct URL from search queries", (t) => {
46 | const queryResultPairs = [
47 | // empty search
48 | ["", undefined],
49 |
50 | // a search with initial spaces, is not modified
51 | [" ", "https://duckduckgo.com/?q=%20%20%20%20"],
52 |
53 | // some of the symbols
54 | ["!m brazil", "https://www.google.com/maps/search/brazil"],
55 | ["!g brazil", "https://encrypted.google.com/search?q=brazil"],
56 | ["!r4 my radio", "https://radio4000.com/search?search=my%20radio"],
57 | ["&gh internet4000/radio4000", "https://github.com/internet4000/radio4000"],
58 | ["&gh internet4000 radio4000", "https://github.com/internet4000/radio4000"],
59 | [
60 | "+r4 https://www.youtube.com/watch?v=sZZlQqG7hEg",
61 | "https://radio4000.com/add?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsZZlQqG7hEg",
62 | ],
63 | ].forEach(([query, result]) => {
64 | const success = t.is(Find.decodeUserRequest(query).result, result);
65 | });
66 | });
67 |
68 | test("Find.addEngine adds a new engine", (t) => {
69 | Find.addEngine(Find.symbols, "!", "ex", "https://example.org");
70 | const res = Find.symbols["!"].engines["ex"];
71 | t.is(res, "https://example.org");
72 | });
73 |
74 | test("Find.delEngine removes an engine", (t) => {
75 | Find.addEngine(Find.symbols, "!", "ex", "https://example.org");
76 | Find.delEngine(Find.symbols, "!", "ex");
77 | const res = Find.symbols["!"].engines["ex"];
78 | t.falsy(res);
79 | });
80 |
81 | test("Find.decodeUserRequest gives correct results", (t) => {
82 | const decoded = Find.decodeUserRequest("&gh internet4000 find");
83 | t.deepEqual(decoded.tokens, ["&gh"]);
84 | t.is(decoded.symbolGroup, "&gh");
85 | t.is(decoded.symbol, "&");
86 | t.is(decoded.engineId, "gh");
87 | t.is(decoded.result, "https://github.com/internet4000/find");
88 | });
89 |
90 | test("Find.replaceUrlPlaceholders gives correct results", (t) => {
91 | const decoded = Find.decodeUserRequest("&gh internet4000 radio4000");
92 | t.is(decoded.result, "https://github.com/internet4000/radio4000");
93 | });
94 |
95 | test("Find has a init method", (t) => {
96 | t.is(Find.init(), undefined);
97 | });
98 |
99 | test("Find.getEngineUrl returns correct results", (t) => {
100 | t.is(
101 | Find.getEngineUrl(Find.symbols, "!", "g"),
102 | "https://encrypted.google.com/search?q={}"
103 | );
104 | t.is(Find.getEngineUrl(Find.symbols, "!", "doesntexist"), undefined);
105 | });
106 |
107 | test("Find.buildEngineResultUrl has a default url result", (t) => {
108 | const url = Find.buildEngineResultUrl("hello");
109 | t.is(url, "https://duckduckgo.com/?q=hello");
110 | });
111 |
112 | test("find handles initial URLSearchParams", (t) => {
113 | window.location = new URL("https://example.org/?q=test");
114 | const res = Find.init();
115 | t.is(res, "https://duckduckgo.com/?q=test");
116 | });
117 |
118 | test("find handles initial query in `#` hash URL", (t) => {
119 | window.location = new URL("https://example.org/#q=test");
120 | const res = Find.init();
121 | t.is(res, "https://duckduckgo.com/?q=test");
122 | });
123 |
--------------------------------------------------------------------------------
/src/tests/open-search-xml.js:
--------------------------------------------------------------------------------
1 | import test from "ava";
2 | import find, { I4kFind } from "../index.js";
3 | import { OpenSearchDescription } from "../open-search.js"
4 | import openSearchXml from '../scripts/opensearch-xml.js'
5 |
6 | const TEST_XML = `
7 |
8 | UTF-8
9 | Find
10 | Find search
11 | https://test.local/my-find/assets/favicon.ico
12 |
13 |
14 |
15 | `;
16 |
17 | test.afterEach(() => {
18 | process.env.I4K_FIND_URL = '';
19 | })
20 |
21 | test("Setting I4K_FIND_URL generates the OpenSearch XML", async (t) => {
22 | process.env.I4K_FIND_URL = 'https://test.local/my-find';
23 | const osdXml = await openSearchXml()
24 | t.deepEqual(osdXml, TEST_XML);
25 | })
26 |
--------------------------------------------------------------------------------
/src/tests/open-search.js:
--------------------------------------------------------------------------------
1 | import test from "ava";
2 | import find, { I4kFind } from "../index.js";
3 | import { OpenSearchDescription } from "../open-search.js"
4 |
5 | const TEST_CONFIG = {
6 | shortName: "Find",
7 | description: "Find search",
8 | image: "https://example.local/test-find/assets/favicon.ico",
9 | templateHTML: "https://example.local/test-find/#q={searchTerms}",
10 | templateXML: "https://example.local/test-find/assets/opensearch.xml",
11 | templateSuggestions:
12 | "https://example.local/test-find/api/suggestions/#q={searchTerms}",
13 | };
14 |
15 | const TEST_XML = `
16 |
17 | UTF-8
18 | Find
19 | Find search
20 | https://example.local/test-find/assets/favicon.ico
21 |
22 |
23 |
24 | `;
25 | /* https://example.local/test-find/#q={searchTerms} */
26 |
27 | test("OpenSearch can export to JSON data", (t) => {
28 | const myOsd = new OpenSearchDescription({...TEST_CONFIG})
29 | t.like(JSON.parse(myOsd.exportJSON()), TEST_CONFIG);
30 | });
31 |
32 | test("OpenSearch can export to XML data", (t) => {
33 | const myOsd = new OpenSearchDescription({...TEST_CONFIG})
34 | t.deepEqual(myOsd.exportXML(), TEST_XML);
35 | });
36 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-analytics.js:
--------------------------------------------------------------------------------
1 | export default class I4kFindAnalytics extends HTMLElement {
2 | CFBeaconSrc = "https://static.cloudflareinsights.com/beacon.min.js";
3 |
4 | get dnt() {
5 | return navigator.doNotTrack;
6 | }
7 | get CFBeacon() {
8 | return this.getAttribute("cf-beacon") || undefined;
9 | }
10 |
11 | async connectedCallback() {
12 | // check if "do not track", then do not use analytics
13 | if (this.dnt) {
14 | console.info("Do-not-track is activated in this browser");
15 | /* return */
16 | }
17 |
18 | /* check can render script tag (should not, if ublock is activated: our objective) */
19 | if (this.CFBeacon) {
20 | this.renderCFAnalytics();
21 | }
22 | }
23 | disconnectedCallback() {
24 | console.info(
25 | "Analytics trackers are BLOCKED. Removing tracking beacon",
26 | this
27 | );
28 | }
29 | renderCFAnalytics() {
30 | const $script = document.createElement("script");
31 | $script.src = this.CFBeaconSrc;
32 | $script.setAttribute(
33 | "data-cf-beacon",
34 | JSON.stringify({
35 | token: this.CFBeacon,
36 | })
37 | );
38 | $script.addEventListener("load", this.onAnalyticsLoad.bind(this));
39 | $script.addEventListener("error", this.onAnalyticsLoadError.bind(this));
40 | this.append($script);
41 | }
42 | onAnalyticsLoad(event) {
43 | console.info(
44 | 'Analytics trackers are NOT blocked (install "ublock origin") (Cloudflare analytics javascript could be loaded)'
45 | );
46 | this.renderInstallBlocker();
47 | }
48 | onAnalyticsLoadError(error) {
49 | this.remove();
50 | }
51 | renderInstallBlocker() {
52 | const $message = document.createElement("p");
53 | $message.innerText =
54 | "This web browsers does not seem to be blocking analytics and advertisement trackers. Consider installing a blocker for your web-browser:" +
55 | " ";
56 |
57 | const $link = document.createElement("a");
58 | $link.innerText = "uBlock Origin";
59 | $link.href = "https://github.com/gorhill/uBlock/";
60 |
61 | $message.append($link);
62 | this.append($message);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-app.js:
--------------------------------------------------------------------------------
1 | export default class I4kFindApp extends HTMLElement {
2 | /* the cloudflare analytics beacon */
3 | get CFBeacon() {
4 | return this.getAttribute("cf-beacon");
5 | }
6 | connectedCallback() {
7 | this.render();
8 | this._setupColor();
9 |
10 | /* handle search (if it is a command) */
11 | this.querySelector("i4k-find-search").addEventListener(
12 | "findSearch",
13 | this._onFindSearch.bind(this),
14 | );
15 |
16 | /* if we "sync", also refresh the info */
17 | this.querySelector("i4k-find-sync").addEventListener(
18 | "submit",
19 | this._onFindSync.bind(this),
20 | );
21 |
22 | Array.from(this.querySelectorAll("i4k-find-query")).forEach(($button) => {
23 | $button.addEventListener("findQuery", this._onFindQuery.bind(this));
24 | });
25 | }
26 | _onFindSearch(event) {
27 | /* if no output to a search,
28 | it can only be because we have a "valid find command" (# fns)
29 | so we stay on the current page */
30 | if (event.detail.output) {
31 | this.setAttribute("searched", true);
32 | } else {
33 | this.removeAttribute("searched");
34 | }
35 |
36 | /* if we stay on the page after command, let's refresh the info */
37 | this.querySelector("i4k-find-info").refresh();
38 | }
39 | _onFindSync() {
40 | this.querySelector("i4k-find-info").refresh();
41 | }
42 | _onFindQuery(event) {
43 | event.preventDefault();
44 | const { detail } = event;
45 | if (detail) {
46 | const newSearch = document.createElement("i4k-find-search");
47 | newSearch.setAttribute("search", detail);
48 | this.querySelector("i4k-find-search").replaceWith(newSearch);
49 | }
50 | }
51 | _setupColor() {
52 | /* just for some color */
53 | this.randomColor = `#${(0x1000000 + Math.random() * 0xffffff)
54 | .toString(16)
55 | .substr(1, 6)}`;
56 | document.documentElement.style.setProperty(
57 | "--c-bg--random",
58 | this.randomColor,
59 | );
60 | }
61 | render() {
62 | this.innerHTML = `
63 |
64 |
65 |
66 | Example queries
67 |
68 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 | sync
145 |
146 |
147 |
148 | `;
149 |
150 | if (this.CFBeacon) {
151 | const $analytics = document.createElement("i4k-find-analytics");
152 | $analytics.setAttribute("cf-beacon", this.CFBeacon);
153 | this.querySelector(".App-body").append($analytics);
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-info.js:
--------------------------------------------------------------------------------
1 | import Find, { DEFAULT_SYMBOLS } from "../index.js";
2 |
3 | export default class I4kFindInfo extends HTMLElement {
4 | constructor() {
5 | super()
6 | this.open = false;
7 | }
8 | connectedCallback() {
9 | this.render();
10 |
11 | /*
12 | local storage event only triggered from other tabs/windows
13 | https://stackoverflow.com/questions/5370784/localstorage-eventlistener-is-not-called
14 | https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event
15 | */
16 | window.addEventListener("storage", this.onStorage.bind(this));
17 | }
18 | disconnectedCallback() {
19 | window.removeEventListener("storage", this.onStorage.bind(this));
20 | }
21 | onStorage(event) {
22 | // instead of updating the find info here, we do it on "find submit"
23 | console.info(
24 | "storage event",
25 | JSON.parse(window.localStorage.getItem(Find.localStorageKey))
26 | );
27 | }
28 | getSymbolsLength(symbols) {
29 | let length = 0;
30 | Object.values(symbols)
31 | .forEach((symbol) => {
32 | length += symbol.engines ? Object.keys(symbol.engines).length : 0;
33 | });
34 | return length;
35 | }
36 | /* an alias for the public api */
37 | refresh() {
38 | this.render();
39 | }
40 | render() {
41 | this.innerHTML = "";
42 | const userSymbols = Find.getUserSymbols();
43 | this.renderSymbols(Find.symbols, "default");
44 | if (userSymbols) {
45 | this.renderSymbols(userSymbols, "user");
46 | }
47 | }
48 | /* Can be used to render a symbols map,
49 | for example, the "default" or "user" symbols */
50 | renderSymbols(symbolsMap, title) {
51 | /* for each symbol render a symbol list with info */
52 | const $symbols = document.createElement("i4k-symbols-list");
53 | Object.keys(DEFAULT_SYMBOLS)
54 | .filter((symbolId) => !symbolId.endsWith(':'))
55 | .forEach((symbolId) => {
56 | const defaultData = DEFAULT_SYMBOLS[symbolId]
57 | const symbolData = symbolsMap[symbolId]
58 | const {
59 | name: symbolName = defaultData.name,
60 | uri = defaultData.uri,
61 | engines,
62 | fns,
63 | } = symbolData || {};
64 |
65 | /* the info "of the symbol definition" Symbol/Name */
66 | const $symbolInfoDefinition = document.createElement("dl");
67 | $symbolInfoDefinition.title = uri
68 | const $symbolTerm = document.createElement("dt");
69 | const $symbolName = document.createElement("dd");
70 | $symbolTerm.innerText = symbolId;
71 | // user symbols don't have data byt the symbol id, and engines id/url
72 | // only default symbol has data
73 | $symbolName.innerText = symbolName || DEFAULT_SYMBOLS[symbol].name;
74 | $symbolInfoDefinition.append($symbolTerm, $symbolName)
75 |
76 | /* the list engines id/url for this symbol */
77 | const $symbolInfoList = document.createElement("ul");
78 | if (engines && Object.keys(engines).length) {
79 | Object.entries(engines).forEach(([engineName, engineUrl]) => {
80 | const $symbolInfoListItem = document.createElement("li");
81 | const $engineName = document.createElement("em");
82 | $engineName.innerText = `${symbolId}${engineName}`;
83 | const $engineValue = document.createElement("a");
84 | $engineValue.href = engineUrl;
85 | try {
86 | // to be "sure" it is a valid (find) URL and does not contain weird things
87 | new URL(engineUrl)
88 | $engineValue.innerHTML = this.highlightPlaceholders(engineUrl);
89 | } catch(e) {
90 | $engineValue.innerText = engineUrl;
91 | }
92 |
93 | $symbolInfoListItem.append($engineName);
94 | $symbolInfoListItem.append($engineValue);
95 | $symbolInfoList.append($symbolInfoListItem);
96 | });
97 | } else if (!fns) {
98 | const $noSymbolEngineListItem = document.createElement("li");
99 | const $noSymbolEngine = document.createElement("input");
100 | $noSymbolEngine.value = `#add ${symbolId} ex https://example.org/?q={}`;
101 | $noSymbolEngine.readonly = true;
102 | $noSymbolEngine.onclick = ({ target }) => target.select();
103 | $noSymbolEngineListItem.append($noSymbolEngine);
104 | $symbolInfoList.append($noSymbolEngineListItem);
105 | }
106 |
107 | if (fns) {
108 | Object.entries(fns).forEach(([fnName, fn]) => {
109 | const $symbolInfoListItem = document.createElement("li");
110 |
111 | const $engineName = document.createElement("em");
112 | $engineName.innerText = `${symbolId}${fnName}`;
113 | const $engineValue = document.createElement("pre");
114 | $engineValue.innerText = `${fn.toString()}`;
115 |
116 | $symbolInfoListItem.append($engineName);
117 | $symbolInfoListItem.append($engineValue);
118 |
119 | $symbolInfoList.append($symbolInfoListItem);
120 | });
121 | }
122 |
123 | if (!engines && !fns) {
124 | }
125 |
126 | /* append the "definition" and "list" */
127 | const $symbolInfo = document.createElement("article");
128 | $symbolInfo.setAttribute('symbol', symbolId)
129 | $symbolInfo.append($symbolInfoDefinition, $symbolInfoList);
130 | $symbols.append($symbolInfo);
131 | });
132 |
133 | const $detail = document.createElement("details");
134 | const $summary = document.createElement("summary");
135 | const symbolsLen = this.getSymbolsLength(symbolsMap);
136 | $summary.title = "List of Find symbols !+ and engines (id and URL) with URI actions placeholder {} patterns"
137 | $summary.innerText = `${title} [${symbolsLen}]`;
138 |
139 | $detail.append($summary);
140 | $detail.append($symbols);
141 |
142 | this.append($detail);
143 | }
144 |
145 | /* to prevent using innerHTML with a regex, such as `engineUrl.replace(/\{\}/g,"{}")` */
146 | highlightPlaceholders(urlWithPlaceholders) {
147 | // Create a temporary div element
148 | const tempDiv = document.createElement('div');
149 |
150 | // Split the url at the placeholder(s)
151 | const urlParts = urlWithPlaceholders.split("{}");
152 |
153 | // Loop over the urlParts, appending each part and a placeholder after it if it's not the last part
154 | urlParts.forEach((part, index) => {
155 | tempDiv.appendChild(document.createTextNode(part));
156 |
157 | if (index < urlParts.length - 1) {
158 | const mark = document.createElement('mark');
159 | mark.textContent = '{}';
160 | tempDiv.appendChild(mark);
161 | }
162 | });
163 |
164 | // Return the innerHTML of the temporary div element
165 | return tempDiv.innerHTML;
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-logo.js:
--------------------------------------------------------------------------------
1 | export default class I4kFindLogo extends HTMLElement {
2 | r4Logo = `
3 |
21 | `;
22 | connectedCallback() {
23 | this.render();
24 | }
25 | render() {
26 | const $homeLink = document.createElement("a");
27 | $homeLink.classList.add("Title");
28 | $homeLink.title = "Find! (click and refresh the page for docs)";
29 | $homeLink.innerHTML = this.r4Logo;
30 | $homeLink.href = window.location + "?q=!docs usage"
31 | this.append($homeLink);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-query.js:
--------------------------------------------------------------------------------
1 | import Find from "../index.js";
2 |
3 | export default class I4kFindQuery extends HTMLElement {
4 | static get observedAttributes() {
5 | return ["no-open", "q", "query"];
6 | }
7 | get noOpen() {
8 | return this.getAttribute("no-open") === "true";
9 | }
10 | get query() {
11 | return this.getAttribute("q") || this.getAttribute("query");
12 | }
13 |
14 | attributeChangedCallback() {
15 | this._render();
16 | }
17 | connectedCallback() {
18 | this._render();
19 | }
20 | _render() {
21 | this.innerHTML = "";
22 | const $btn = this._createButton();
23 | this.append($btn);
24 | }
25 |
26 | _createButton() {
27 | const $btn = document.createElement("button");
28 | $btn.addEventListener("click", this._onClick.bind(this));
29 | $btn.innerText = this.query;
30 | return $btn;
31 | }
32 |
33 | _onClick(event) {
34 | if (this.query) {
35 | const decodedRequest = Find.decodeUserRequest(this.query);
36 | const { result } = decodedRequest;
37 |
38 | const event = new CustomEvent("findQuery", {
39 | bubbles: true,
40 | detail: this.query,
41 | cancelable: true,
42 | });
43 | this.dispatchEvent(event);
44 |
45 | if (!this.noOpen) {
46 | Find.openUrl(result);
47 | }
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-search.js:
--------------------------------------------------------------------------------
1 | import Find from "../index.js";
2 |
3 | export default class I4kFindSearch extends HTMLElement {
4 | static get observedAttributes() {
5 | return ["search"];
6 | }
7 | get search() {
8 | return this.getAttribute("search") || "";
9 | }
10 | set search(str) {
11 | this.setAttribute("search", str);
12 | }
13 | connectedCallback() {
14 | this._render();
15 | }
16 | findSearch = (query) => {
17 | if (!query) return false;
18 | const output = Find.find(query);
19 | const event = new CustomEvent("findSearch", {
20 | bubbles: true,
21 | detail: {
22 | query,
23 | output,
24 | },
25 | });
26 | this.dispatchEvent(event);
27 | return output
28 | };
29 | _clearSearch() {
30 | this.querySelector("form input").value = "";
31 | }
32 | _handleSubmit = (event) => {
33 | event.preventDefault();
34 | const output = this.findSearch(this.search);
35 | if (output) {
36 | this._clearSearch();
37 | }
38 | };
39 | _handleInputChange = (input) => {
40 | this[input.target.name] = input.target.value;
41 | this._handleSuggestions(input);
42 | };
43 | _buildRandomPlaceholder() {}
44 |
45 | async _handleSuggestions({ target: { value, name } }) {
46 | if (value) {
47 | const suggestionUrl = `api/suggestions#q=${encodeURIComponent(value)}`;
48 | let suggestions;
49 | try {
50 | const res = await fetch(suggestionUrl);
51 | if (res.status === 200) {
52 | suggestions = await res.json();
53 | }
54 | } catch (e) {
55 | console.info("Error fetching suggestions", e);
56 | }
57 | if (suggestions) {
58 | this._renderSuggestions(suggestions);
59 | }
60 | }
61 | }
62 |
63 | _render() {
64 | this.innerHTML = "";
65 | const $form = document.createElement("form");
66 | $form.title = "Try to write any search words, or the Find query, !m berlin";
67 | $form.addEventListener("submit", this._handleSubmit.bind(this));
68 | $form.classList.add("Form");
69 |
70 | const $input = document.createElement("input");
71 | $input.type = "search";
72 | $input.name = "search";
73 | $input.value = this.search;
74 | $input.required = true;
75 | $input.placeholder = this._buildRandomPlaceholder() || "!docs usage";
76 | $input.setAttribute('title', 'Input a Find search query (any search)');
77 | $input.addEventListener("input", this._handleInputChange.bind(this));
78 | $input.setAttribute("list", "suggestions");
79 |
80 | const $inputData = document.createElement("datalist");
81 | $inputData.id = "suggestions";
82 |
83 | const $button = document.createElement("button");
84 | $button.innerText = "Find";
85 | $button.type = "submit";
86 |
87 | $form.append($input, $inputData, $button);
88 |
89 | this.append($form);
90 | }
91 | _renderSuggestions([query = "", suggestions = []]) {
92 | const [terms, descriptions, urls] = suggestions;
93 | const $datalist = this.querySelector("datalist");
94 | const $suggestions = [];
95 | terms.map((term, termIndex) => {
96 | const $suggestion = document.createElement("option");
97 | $suggestion.value = term;
98 | $suggestion.innerText = `${term} ${descriptions[termIndex]}`;
99 | $suggestions.push($suggestion);
100 | });
101 | $datalist.innerHTML = "";
102 | $datalist.append(...$suggestions);
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/src/ui/i4k-find-sync.js:
--------------------------------------------------------------------------------
1 | import Find from "../index.js";
2 |
3 | export default class I4kFindSync extends HTMLElement {
4 | connectedCallback() {
5 | this.render();
6 | }
7 |
8 | render() {
9 | this.innerHTML = "";
10 | this.renderForm();
11 | }
12 |
13 | renderForm() {
14 | const $form = document.createElement("form");
15 | $form.addEventListener("submit", this.onSubmit.bind(this));
16 |
17 | const $import = document.createElement("textarea");
18 | $import.setAttribute("name", "import");
19 | $import.setAttribute("title", "Paste in the user JSON data to be imported, in order to import it in this instance of find");
20 | $import.setAttribute("required", true);
21 | $import.setAttribute("placeholder", 'exported JSON data, ex: {"userSymbols": {...}}');
22 |
23 | // not used yet
24 | const $importAuto = document.createElement("input");
25 | $importAuto.setAttribute("name", "import-auto");
26 | $importAuto.setAttribute("type", "password");
27 | $importAuto.setAttribute("hidden", true);
28 | $importAuto.setAttribute("autocomplete", "password");
29 | $importAuto.setAttribute("placeholder", "password='appData{userSymbols}'");
30 |
31 | const $syncButton = document.createElement("button");
32 | $syncButton.type = "submit";
33 | $syncButton.innerText = "import user data";
34 |
35 | const $export = document.createElement("textarea");
36 | $export.value = this.getDataToSync();
37 | $export.setAttribute("readonly", true);
38 | $export.setAttribute("title", "User data as a JSON string. Copy to export. Save somewhere (in a text file) to import later, or somewhere else.");
39 | $export.addEventListener("click", this.onCopy.bind(this));
40 |
41 | const $importLabel = document.createElement("legend");
42 | const $exportLabel = document.createElement("legend");
43 | $importLabel.innerText = "Import JSON data"
44 | $exportLabel.innerText = "Export JSON data"
45 |
46 | const $importFieldset = document.createElement("fieldset");
47 | const $exportFieldset = document.createElement("fieldset");
48 | $importFieldset.append($importLabel, $import, $syncButton);
49 | $exportFieldset.append($exportLabel, $export);
50 | $form.append($importAuto, $importFieldset, $exportFieldset, this._createHelp());
51 | this.append($form);
52 | }
53 |
54 | _createHelp() {
55 | const $fieldset = document.createElement("fieldset");
56 | const $legend = document.createElement("legend");
57 | $legend.innerText = "Syncronization flow"
58 | const $text = document.createElement("pre");
59 | $text.innerText = `# Export (save)
60 | 1. Copy JSON data of your user settings
61 | 2. Save as a new entry for this site, in your usual browser password manager
62 | 2. Have the password manager, like for password, synchronise the data between your devices
63 |
64 | # Import (for a new device/browser)
65 | 1. when saved, prefill the import input, from the password manager, like for a password (it is your "private user search engines" after all)
66 | 2. Click the import button, to add all engines
67 |
68 | # Recommendations:
69 | - Always import first, before editing your exising search engines
70 | - Always export/(auto,manual)sync to your (browser) password manager, after any edit
71 | `;
72 | $fieldset.append($legend, $text);
73 | return $fieldset
74 | }
75 |
76 | onCopy({ target }) {
77 | const data = this.getDataToSync();
78 | target.focus();
79 | target.select();
80 | }
81 |
82 | onSubmit(event) {
83 | event.preventDefault();
84 | /* the data, is the one submitted by the user, to import in the app;
85 | from filling the input with the "credentials" (in our case, just app data) */
86 | const formData = new FormData(event.target);
87 | this.syncCredentials(formData);
88 | this.syncLoginForm(formData);
89 | event.target.reset()
90 | this.render()
91 | }
92 |
93 | /* TODO: not working yet
94 | Save to the browser credentials / password mananger */
95 | async syncCredentials() {
96 | if ("credentials" in navigator) {
97 | let creds;
98 | try {
99 | creds = await navigator.credentials.get({
100 | password: true, // `true` to obtain password credentials
101 | federated: {
102 | providers: [
103 | // Specify an array of IdP strings
104 | window.location.hostname,
105 | ],
106 | },
107 | });
108 | } catch (e) {
109 | /* console.info("Credentials API not supported", e); */
110 | }
111 | }
112 | }
113 |
114 | /* a method, to import/export the app user data */
115 | syncLoginForm(formData) {
116 | const newDataAutoRaw = formData.get("import-auto");
117 | const newDataRaw = formData.get("import");
118 | let newDataJson;
119 | if (newDataRaw) {
120 | try {
121 | newDataJson = JSON.parse(newDataRaw);
122 | } catch (e) {
123 | console.error("data to import is not a JSON string ", e);
124 | }
125 | }
126 | if (!newDataJson) return;
127 | const { userSymbols } = newDataJson;
128 | Find.importUserSymbols(userSymbols);
129 | console.info("newData imported", userSymbols, Find.getUserSymbols());
130 | }
131 |
132 | getDataToSync() {
133 | return JSON.stringify({
134 | userSymbols: Find.getUserSymbols(),
135 | });
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/ui/index.js:
--------------------------------------------------------------------------------
1 | import i4kFindSearch from "./i4k-find-search.js";
2 | import i4kFindQuery from "./i4k-find-query.js";
3 | import i4kFindSync from "./i4k-find-sync.js";
4 | import i4kFindInfo from "./i4k-find-info.js";
5 | import i4kFindLogo from "./i4k-find-logo.js";
6 | import i4kFindAnalytics from "./i4k-find-analytics.js";
7 | import i4kFindApp from "./i4k-find-app.js";
8 |
9 | const componentDefinitions = {
10 | "i4k-find-search": i4kFindSearch,
11 | "i4k-find-query": i4kFindQuery,
12 | "i4k-find-sync": i4kFindSync,
13 | "i4k-find-info": i4kFindInfo,
14 | "i4k-find-logo": i4kFindLogo,
15 | "i4k-find-analytics": i4kFindAnalytics,
16 | "i4k-find-app": i4kFindApp,
17 | };
18 |
19 | export function defineComponents(components = []) {
20 | if (components.length === 0) {
21 | components = [...Object.keys(componentDefinitions)];
22 | }
23 | for (const [componentName, componentClass] of Object.entries(
24 | componentDefinitions
25 | )) {
26 | if (
27 | !customElements.get(componentName) &&
28 | components.includes(componentName)
29 | ) {
30 | customElements.define(componentName, componentClass);
31 | }
32 | }
33 | }
34 |
35 | defineComponents();
36 |
37 | export default componentDefinitions;
38 |
--------------------------------------------------------------------------------