@yaks/names 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Jeff Peterson
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ # @yaks/names
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vocabulary-based display names and fuzzy name matching. The caller supplies
4
+ candidate entities; this package does not query storage or enforce name
5
+ uniqueness.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ deno add jsr:@yaks/names
11
+ # or: npx jsr add @yaks/names
12
+ ```
13
+
14
+ ## Selecting name fields
15
+
16
+ Only fields explicitly declared with `by_name` participate in name resolution. A
17
+ text field such as a review body should not become an entity name merely because
18
+ it contains matching words.
19
+
20
+ ## The `by_name` keyword
21
+
22
+ This package owns one keyword. A component that declares `"by_name": true` makes
23
+ its entities addressable by name, read from the vocabulary's name property
24
+ (`doc.title` by default); a string names a different property, with its
25
+ component.
26
+
27
+ ```json
28
+ {
29
+ "$vocabulary": {
30
+ "https://yak.sh/vocab/core": true,
31
+ "https://yak.sh/vocab/names": true
32
+ },
33
+ "$defs": {
34
+ "author": {
35
+ "type": "object",
36
+ "component": true,
37
+ "kind": true,
38
+ "by_name": true
39
+ },
40
+ "shelf": {
41
+ "type": "object",
42
+ "component": true,
43
+ "kind": true,
44
+ "by_name": "shelf.label",
45
+ "properties": { "label": { "type": "string" } }
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ Load that document, here `catalog`, with the `doc` schema for its `title` field,
52
+ and register the keyword vocabulary:
53
+
54
+ ```ts
55
+ import { loadVocab } from '@yaks/vocab'
56
+ import { named, nameKeywords, nameOf, resolve } from '@yaks/names'
57
+ import { docDoc } from '@yaks/doc'
58
+
59
+ let catalog = {
60
+ $defs: {
61
+ author: { component: true, kind: true, by_name: true },
62
+ review: { component: true, kind: true },
63
+ },
64
+ }
65
+ let v = loadVocab([docDoc, catalog], [nameKeywords])
66
+ let shelf = [
67
+ { comps: { author: {}, doc: { title: 'Ursula Le Guin' } } },
68
+ { comps: { review: {}, doc: { title: 'Ursula at her best' } } },
69
+ ]
70
+
71
+ named(v) // { author: { comp: 'doc', prop: 'title' } }
72
+ nameOf(v)(shelf[0]) // 'Ursula Le Guin'
73
+ nameOf(v)(shelf[1]) // undefined — a review's title is not a name
74
+ resolve(v)('le guin', shelf) // the author
75
+ ```
76
+
77
+ A candidate is any object with its components under `comps`, and you get your
78
+ own object back — the package reads the vocabulary and the name, never your row
79
+ type.
80
+
81
+ ## Matching
82
+
83
+ Names are normalized to lowercase ASCII letters and digits, ignoring spaces and
84
+ punctuation. The highest score at or above the threshold wins; tied scores
85
+ return the first candidate. `CLOSE` defaults to `0.6`. Matching compares the
86
+ full name and a discounted first-word abbreviation. Pass `{ close: 1 }` to
87
+ require equality after normalization, not byte-for-byte equality.
88
+
89
+ `match.ts` is the scoring on its own — `score`, `closeness`, `nearest` — usable
90
+ over any list, in case you want the same definition of "close enough" elsewhere
91
+ (in a did-you-mean suggestion, say). Two conditions keep substring matching from
92
+ firing on coincidence: the shorter string must cover most of the longer name,
93
+ and a string that is a prefix scores higher than one that merely appears
94
+ somewhere inside, because a prefix is how a name usually gets shortened.
95
+
96
+ ## Exports
97
+
98
+ | export | is |
99
+ | ---------------------------------------- | ------------------------------------------------------- |
100
+ | `nameKeywords`, `NAMES_URI` | the `by_name` keyword vocabulary, ready to register |
101
+ | `named(v)` | every component addressable by name → its name property |
102
+ | `nameOf(v)` | an entity → its name, or nothing when it has none |
103
+ | `resolve(v)` | a typed name + candidates → the entity it refers to |
104
+ | `score`, `closeness`, `nearest`, `CLOSE` | the matching, on its own |
105
+
106
+ ## Integration
107
+
108
+ An extension of [@yaks/vocab](https://jsr.io/@yaks/vocab): the meta-model
109
+ carries the `by_name` keyword without interpreting it, and this package supplies
110
+ the interpretation. It sits beside [@yaks/id](https://jsr.io/@yaks/id), which
111
+ owns the other way an entity is addressed — the human id (`B-7`) a person types.
112
+
113
+ ## Compatibility
114
+
115
+ Pure TypeScript. Its only dependency is
116
+ [@yaks/vocab](https://jsr.io/@yaks/vocab) (types plus a loaded schema). Runs on
117
+ **Deno**, **Node**, and in the **browser**.
@@ -0,0 +1,8 @@
1
+ import type { Keywords } from "@yaks/vocab";
2
+ /** The URI a vocab file declares under `$vocabulary` to use `by_name`. */ export declare let NAMES_URI: string;
3
+ /**
4
+ * The `by_name` keyword vocabulary, ready to register:
5
+ * `loadVocab(docs, [nameKeywords])` copies each component's declaration onto
6
+ * `v.comp(name).keywords.by_name`, which is where `named()` reads it.
7
+ */ export declare let nameKeywords: Keywords;
8
+ //# sourceMappingURL=keywords.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keywords.d.ts","sources":["../keywords.ts"],"names":[],"mappings":"AAKA,cAAc,QAAQ,2BAAgC;AAGtD,wEAAwE,GACxE,OAAO,YAAI,kBAAwC;AAEnD;;;;CAIC,GACD,OAAO,YAAI,cAAc,SAIxB"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * How close a typed word is to a name, from 0 (nothing) to 1 (the same name).
3
+ * Both sides are normalized first, so case and punctuation never decide.
4
+ */ export declare let score: (typed: string, name: string) => number;
5
+ /**
6
+ * The strings a candidate can be matched by, and what each is worth: the whole
7
+ * name, and its first word — which is how a name gets shortened
8
+ * (`Ursula Le Guin` → `ursula`). Words in the middle are excluded: scoring them
9
+ * would let a common word buried in a long name win outright, and in a large
10
+ * store there is always such a word.
11
+ */ export declare let answers: (name: string) => [string, number][];
12
+ /** How close a typed word is to a candidate, across every string it can be
13
+ * matched by. */ export declare let closeness: (typed: string, name: string) => number;
14
+ /**
15
+ * The score at which a match is close enough to be the name that was intended.
16
+ * Below this, a guess is noise, and returning nothing is more useful.
17
+ */ export declare let CLOSE: number;
18
+ /**
19
+ * The candidate whose name is closest to what was typed, or nothing when none
20
+ * is close enough. `name` reads a candidate's name (a candidate with none is
21
+ * skipped); `close` is the threshold the winner must clear — pass 1 to accept
22
+ * exact names only.
23
+ */ export declare let nearest: <T>(typed: string, among: T[], name: (x: T) => string | undefined) => T | undefined;
24
+ //# sourceMappingURL=match.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"match.d.ts","sources":["../match.ts"],"names":[],"mappings":"AAgEA;;;CAGC,GACD,OAAO,YAAI,QAAS,OAAO,MAAM,EAAE,MAAM,MAAM,KAAG,MAAM,CAIvD;AAED;;;;;;CAMC,GACD,OAAO,YAAI,UAAW,MAAM,MAAM,MAAI,MAAM,EAAE,MAAM,IAGnD;AAED;eACe,GACf,OAAO,YAAI,YAAa,OAAO,MAAM,EAAE,MAAM,MAAM,KAAG,MAAM,CACa;AAEzE;;;CAGC,GACD,OAAO,YAAI,cAAW;AAEtB;;;;;CAKC,GACD,OAAO,YAAI,UAAW,GACpB,OAAO,MAAM,EACb,OAAO,KACP,OAAO,GAAG,MAAM,MAAM,GAAG,SAAS,KAEjC,IAAI,SAAS,CASf"}
package/_dist/mod.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @yaks/names — resolve an entity by name.
3
+ *
4
+ * ## Not everything has a name
5
+ * An author is found by typing `Ursula Le Guin`. A review is not found by the
6
+ * sentence it opens with, even though it has a title too: a word buried in a
7
+ * store's prose matches by coincidence, and in a large store there is always
8
+ * one such word. So each component declares which case it is.
9
+ *
10
+ * ## The `by_name` keyword This package owns one keyword. A component that
11
+ * declares `"by_name": true` makes its entities addressable by name, read from
12
+ * the vocabulary's name property (`doc.title` by default); a string names a
13
+ * different property, with its component (`"by_name": "shelf.label"`).
14
+ *
15
+ * ```json
16
+ * { "$defs": { "author": { "type": "object", "kind": true, "by_name": true } } }
17
+ * ```
18
+ *
19
+ * Register it when you load the vocabulary, and names resolve:
20
+ *
21
+ * ```ts
22
+ * import { loadVocab } from '@yaks/vocab'
23
+ * import { docDoc } from '@yaks/doc'
24
+ * import { nameKeywords, named, nameOf, resolve } from '@yaks/names'
25
+ *
26
+ * let catalog = {
27
+ * $defs: {
28
+ * author: { component: true, kind: true, by_name: true },
29
+ * review: { component: true, kind: true },
30
+ * },
31
+ * }
32
+ * let v = loadVocab([docDoc, catalog], [nameKeywords])
33
+ * let shelf = [
34
+ * { comps: { author: {}, doc: { title: 'Ursula Le Guin' } } },
35
+ * { comps: { review: {}, doc: { title: 'Ursula at her best' } } },
36
+ * ]
37
+ *
38
+ * named(v) // { author: { comp: 'doc', prop: 'title' } }
39
+ * nameOf(v)(shelf[0]) // 'Ursula Le Guin'
40
+ * nameOf(v)(shelf[1]) // undefined — a review's title is not a name
41
+ * resolve(v)('le guin', shelf) // the author
42
+ * ```
43
+ *
44
+ * An exact name always wins; failing that, the closest name above the match
45
+ * threshold does, because nobody types a name exactly as it is stored — the
46
+ * case drifts, the punctuation is dropped, a long name gets abbreviated to its
47
+ * first word. Pass `{ close: 1 }` to accept exact names only.
48
+ *
49
+ * The pieces:
50
+ * - `keywords.ts` — the `by_name` keyword vocabulary, ready to register
51
+ * - `names.ts` — what the vocabulary declares: which components are addressable
52
+ * by name, which property holds the name, and which entity a typed name
53
+ * refers to
54
+ * - `match.ts` — the scoring, on its own: how close two names are
55
+ *
56
+ * @module
57
+ */ export * from "./keywords.js";
58
+ export * from "./match.js";
59
+ export * from "./names.js";
60
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDC,GAED,8BAA6B;AAC7B,2BAA0B;AAC1B,2BAA0B"}
@@ -0,0 +1,36 @@
1
+ import type { Hop, Vocab } from "@yaks/vocab";
2
+ /** An entity as this package reads it: component name → that component's
3
+ * properties. Any other fields are left untouched, so a caller's own row type
4
+ * works as long as its components are under `comps`. */ export type Comps = Record<string, Record<string, unknown> | undefined>;
5
+ /** The shape a candidate must have to be resolved: the components it carries. */ export type Carried = {
6
+ comps: Comps;
7
+ };
8
+ /** How names are read: `prop` is the default name property, named with its
9
+ * component (`doc.title` unless said), and `close` is the match threshold — 1
10
+ * accepts exact names only. */ export type Opts = {
11
+ prop?: string;
12
+ close?: number;
13
+ };
14
+ /**
15
+ * Every component addressable by name, mapped to the property holding it:
16
+ * `{ author: { comp: 'doc', prop: 'title' } }`. Reads the `by_name` keyword, so
17
+ * the vocabulary must have been loaded with `nameKeywords` registered — an
18
+ * unregistered keyword is invisible to the loader.
19
+ */ export declare let named: (v: Vocab, opts?: Opts) => Record<string, Hop>;
20
+ /**
21
+ * An entity's name, or nothing when it has none. Config-first over a loaded
22
+ * vocabulary: `let name = nameOf(v)`, then `name(author)`. An entity has a name
23
+ * when it carries a component declared `by_name` and the property that
24
+ * declaration points at holds a string — so the same `doc.title` is a name on
25
+ * an author and merely text on a review.
26
+ */ export declare let nameOf: (v: Vocab, opts?: Opts) => (e: Carried) => string | undefined;
27
+ /**
28
+ * The entity a typed name refers to, or nothing when none is close enough.
29
+ * Config-first: `let byName = resolve(v)`, then `byName('le guin', authors)`.
30
+ *
31
+ * An exact name always wins. Failing that, the closest name above the match
32
+ * threshold wins, because nobody types a name exactly as it is stored — pass
33
+ * `{ close: 1 }` for exact names only. Candidates with no name are skipped, so
34
+ * a store's prose can never be matched by a word inside it.
35
+ */ export declare let resolve: (v: Vocab, opts?: Opts) => <T extends Carried>(name: string, among: T[]) => T | undefined;
36
+ //# sourceMappingURL=names.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"names.d.ts","sources":["../names.ts"],"names":[],"mappings":"AASA,cAAc,GAAG,EAAE,KAAK,2BAAgC;AAGxD;;sDAEsD,GACtD,YAAY,QAAQ,OAAO,MAAM,EAAE,OAAO,MAAM,EAAE,OAAO,IAAI,SAAS;AAEtE,+EAA+E,GAC/E,YAAY;EAAY,OAAO;;AAE/B;;6BAE6B,GAC7B,YAAY;EAAS,OAAO,MAAM;EAAE,QAAQ,MAAM;;AAmBlD;;;;;CAKC,GACD,OAAO,YAAI,QAAS,GAAG,OAAO,OAAM,SAAY,OAAO,MAAM,EAAE,KAW9D;AAED;;;;;;CAMC,GACD,OAAO,YAAI,SACT,GAAG,OACH,OAAM,UACJ,GAAG,YAAY,MAAM,GAAG,SAAS,CAUpC;AAED;;;;;;;;CAQC,GACD,OAAO,YAAI,UACT,GAAG,OACH,OAAM,UACJ,UAAU,SAAS,MAAM,MAAM,EAAE,OAAO,QAAQ,IAAI,SAAS,CAIhE"}
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/names","version":"0.2.36","license":"Apache-2.0","description":"Resolves entity names from the properties a component vocabulary marks for name lookup.","exports":"./mod.ts","imports":{"@yaks/names":"./mod.ts"}}
package/keywords.js ADDED
@@ -0,0 +1,20 @@
1
+ // The registration: what @yaks/names adds to a component vocabulary, written in
2
+ // JSON Schema's own extension form. `meta/names.vocab.json` is the authored
3
+ // source (the keyword's schema and its documentation); this module gives it a
4
+ // name and the shape `loadVocab(docs, [nameKeywords])` expects.
5
+ import doc from './meta/names.vocab.json' with {
6
+ type: 'json'
7
+ };
8
+ /** The URI a vocab file declares under `$vocabulary` to use `by_name`. */ export let NAMES_URI = 'https://yak.sh/vocab/names';
9
+ /**
10
+ * The `by_name` keyword vocabulary, ready to register:
11
+ * `loadVocab(docs, [nameKeywords])` copies each component's declaration onto
12
+ * `v.comp(name).keywords.by_name`, which is where `named()` reads it.
13
+ */ export let nameKeywords = {
14
+ uri: NAMES_URI,
15
+ comp: [
16
+ 'by_name'
17
+ ],
18
+ doc
19
+ };
20
+ //# sourceMappingURL=keywords.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keywords.js","sources":["./keywords.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,4EAA4E;AAC5E,8EAA8E;AAC9E,gEAAgE;AAGhE,OAAO,SAAS,+BAA+B;EAAE,MAAM;AAAO,EAAC;AAE/D,wEAAwE,GACxE,OAAO,IAAI,YAAY,6BAA4B;AAEnD;;;;CAIC,GACD,OAAO,IAAI,eAAyB;EAClC,KAAK;EACL,MAAM;IAAC;GAAU;EACjB;AACF,EAAC"}
package/keywords.ts ADDED
@@ -0,0 +1,21 @@
1
+ // The registration: what @yaks/names adds to a component vocabulary, written in
2
+ // JSON Schema's own extension form. `meta/names.vocab.json` is the authored
3
+ // source (the keyword's schema and its documentation); this module gives it a
4
+ // name and the shape `loadVocab(docs, [nameKeywords])` expects.
5
+
6
+ import type { Keywords } from 'jsr:@yaks/vocab@0.2.36'
7
+ import doc from './meta/names.vocab.json' with { type: 'json' }
8
+
9
+ /** The URI a vocab file declares under `$vocabulary` to use `by_name`. */
10
+ export let NAMES_URI = 'https://yak.sh/vocab/names'
11
+
12
+ /**
13
+ * The `by_name` keyword vocabulary, ready to register:
14
+ * `loadVocab(docs, [nameKeywords])` copies each component's declaration onto
15
+ * `v.comp(name).keywords.by_name`, which is where `named()` reads it.
16
+ */
17
+ export let nameKeywords: Keywords = {
18
+ uri: NAMES_URI,
19
+ comp: ['by_name'],
20
+ doc,
21
+ }
package/match.js ADDED
@@ -0,0 +1,112 @@
1
+ // Matching a name someone typed against the names available. Nobody types a
2
+ // name exactly as it is stored — the case drifts, the punctuation is dropped, a
3
+ // long name gets abbreviated to its first word — so an exact string comparison
4
+ // returns "no such author" far too often.
5
+ //
6
+ // This is scoring only. Which entities are addressable by name, and which
7
+ // property holds the name, is names.ts; what to do with the winner is up to the
8
+ // caller.
9
+ // Two names are compared with both stripped: case, spaces and punctuation carry
10
+ // no meaning in a typed name ('le-guin' and 'Le Guin' find the same entity).
11
+ let norm = (s)=>s.toLowerCase().replace(/[^a-z0-9]+/g, '');
12
+ // What two names share at either end costs no edit, so only the middle between
13
+ // is measured: `harnes` against `harness` is one insertion, found without a
14
+ // table.
15
+ let middle = (a, b)=>{
16
+ let i = 0;
17
+ while(i < a.length && i < b.length && a[i] == b[i])i++;
18
+ let j = 0;
19
+ while(j < a.length - i && j < b.length - i && a[a.length - 1 - j] == b[b.length - 1 - j])j++;
20
+ return [
21
+ a.slice(i, a.length - j),
22
+ b.slice(i, b.length - j)
23
+ ];
24
+ };
25
+ // Levenshtein distance, one row at a time — over a single name, so the naive
26
+ // table is the right size.
27
+ let dist = (x, y)=>{
28
+ let [a, b] = middle(x, y);
29
+ if (!a || !b) return a.length + b.length;
30
+ let row = [];
31
+ for(let j = 0; j <= b.length; j++)row.push(j);
32
+ for(let i = 1; i <= a.length; i++){
33
+ let prev = row[0];
34
+ row[0] = i;
35
+ for(let j = 1; j <= b.length; j++){
36
+ let swap = row[j];
37
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] == b[j - 1] ? 0 : 1));
38
+ prev = swap;
39
+ }
40
+ }
41
+ return row[b.length];
42
+ };
43
+ // What a substring match is worth, and 0 when there is none. It earns its place
44
+ // because edit distance alone treats a longer name as unrelated — `earthsea`
45
+ // against `A Wizard of Earthsea` scores close to nothing. Two conditions keep it
46
+ // from firing on coincidence: the shorter string must cover most of the longer
47
+ // one (otherwise `le` is inside half the shelf), and a prefix scores higher than
48
+ // a substring appearing anywhere else, because a prefix is how a name usually
49
+ // gets abbreviated.
50
+ let within = (a, b)=>{
51
+ let [small, big] = a.length < b.length ? [
52
+ a,
53
+ b
54
+ ] : [
55
+ b,
56
+ a
57
+ ];
58
+ if (small.length < 3 || !big.includes(small)) return 0;
59
+ if (small.length * 2 < big.length) return 0;
60
+ return big.startsWith(small) ? 0.9 : 0.7;
61
+ };
62
+ /**
63
+ * How close a typed word is to a name, from 0 (nothing) to 1 (the same name).
64
+ * Both sides are normalized first, so case and punctuation never decide.
65
+ */ export let score = (typed, name)=>{
66
+ let [a, b] = [
67
+ norm(typed),
68
+ norm(name)
69
+ ];
70
+ return !a || !b ? 0 : a == b ? 1 : within(a, b) || 1 - dist(a, b) / Math.max(a.length, b.length);
71
+ };
72
+ /**
73
+ * The strings a candidate can be matched by, and what each is worth: the whole
74
+ * name, and its first word — which is how a name gets shortened
75
+ * (`Ursula Le Guin` → `ursula`). Words in the middle are excluded: scoring them
76
+ * would let a common word buried in a long name win outright, and in a large
77
+ * store there is always such a word.
78
+ */ export let answers = (name)=>[
79
+ [
80
+ name,
81
+ 1
82
+ ],
83
+ [
84
+ name.split(/\s+/)[0] ?? '',
85
+ 0.85
86
+ ]
87
+ ];
88
+ /** How close a typed word is to a candidate, across every string it can be
89
+ * matched by. */ export let closeness = (typed, name)=>Math.max(...answers(name).map(([w, worth])=>worth * score(typed, w)));
90
+ /**
91
+ * The score at which a match is close enough to be the name that was intended.
92
+ * Below this, a guess is noise, and returning nothing is more useful.
93
+ */ export let CLOSE = 0.6;
94
+ /**
95
+ * The candidate whose name is closest to what was typed, or nothing when none
96
+ * is close enough. `name` reads a candidate's name (a candidate with none is
97
+ * skipped); `close` is the threshold the winner must clear — pass 1 to accept
98
+ * exact names only.
99
+ */ export let nearest = (typed, among, name, close = CLOSE)=>{
100
+ let best;
101
+ for (let x of among){
102
+ let n = name(x);
103
+ if (!n) continue;
104
+ let hit = closeness(typed, n);
105
+ if (hit >= close && (!best || hit > best[1])) best = [
106
+ x,
107
+ hit
108
+ ];
109
+ }
110
+ return best?.[0];
111
+ };
112
+ //# sourceMappingURL=match.js.map
package/match.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"match.js","sources":["./match.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,gFAAgF;AAChF,+EAA+E;AAC/E,0CAA0C;AAC1C,EAAE;AACF,0EAA0E;AAC1E,gFAAgF;AAChF,UAAU;AAEV,gFAAgF;AAChF,6EAA6E;AAC7E,IAAI,OAAO,CAAC,IAAc,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe;AAEjE,+EAA+E;AAC/E,4EAA4E;AAC5E,SAAS;AACT,IAAI,SAAS,CAAC,GAAW;EACvB,IAAI,IAAI;EACR,MAAO,IAAI,EAAE,MAAM,IAAI,IAAI,EAAE,MAAM,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,CAAE;EACrD,IAAI,IAAI;EACR,MACE,IAAI,EAAE,MAAM,GAAG,KAAK,IAAI,EAAE,MAAM,GAAG,KACnC,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,CAC1C;EACF,OAAO;IAAC,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG;IAAI,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG;GAAG;AAC7D;AAEA,6EAA6E;AAC7E,2BAA2B;AAC3B,IAAI,OAAO,CAAC,GAAW;EACrB,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,GAAG;EACvB,IAAI,CAAC,KAAK,CAAC,GAAG,OAAO,EAAE,MAAM,GAAG,EAAE,MAAM;EACxC,IAAI,MAAgB,EAAE;EACtB,IAAK,IAAI,IAAI,GAAG,KAAK,EAAE,MAAM,EAAE,IAAK,IAAI,IAAI,CAAC;EAC7C,IAAK,IAAI,IAAI,GAAG,KAAK,EAAE,MAAM,EAAE,IAAK;IAClC,IAAI,OAAO,GAAG,CAAC,EAAE;IACjB,GAAG,CAAC,EAAE,GAAG;IACT,IAAK,IAAI,IAAI,GAAG,KAAK,EAAE,MAAM,EAAE,IAAK;MAClC,IAAI,OAAO,GAAG,CAAC,EAAE;MACjB,GAAG,CAAC,EAAE,GAAG,KAAK,GAAG,CACf,GAAG,CAAC,EAAE,GAAG,GACT,GAAG,CAAC,IAAI,EAAE,GAAG,GACb,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC;MAEtC,OAAO;IACT;EACF;EACA,OAAO,GAAG,CAAC,EAAE,MAAM,CAAC;AACtB;AAEA,gFAAgF;AAChF,6EAA6E;AAC7E,iFAAiF;AACjF,+EAA+E;AAC/E,iFAAiF;AACjF,8EAA8E;AAC9E,oBAAoB;AACpB,IAAI,SAAS,CAAC,GAAW;EACvB,IAAI,CAAC,OAAO,IAAI,GAAG,EAAE,MAAM,GAAG,EAAE,MAAM,GAAG;IAAC;IAAG;GAAE,GAAG;IAAC;IAAG;GAAE;EACxD,IAAI,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,QAAQ,CAAC,QAAQ,OAAO;EACrD,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,MAAM,EAAE,OAAO;EAC1C,OAAO,IAAI,UAAU,CAAC,SAAS,MAAM;AACvC;AAEA;;;CAGC,GACD,OAAO,IAAI,QAAQ,CAAC,OAAe;EACjC,IAAI,CAAC,GAAG,EAAE,GAAG;IAAC,KAAK;IAAQ,KAAK;GAAM;EACtC,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,GAAG,MAC3C,IAAI,KAAK,GAAG,KAAK,KAAK,GAAG,CAAC,EAAE,MAAM,EAAE,EAAE,MAAM;AAChD,EAAC;AAED;;;;;;CAMC,GACD,OAAO,IAAI,UAAU,CAAC,OAAqC;IACzD;MAAC;MAAM;KAAE;IACT;MAAC,KAAK,KAAK,CAAC,MAAM,CAAC,EAAE,IAAI;MAAI;KAAK;GACnC,CAAA;AAED;eACe,GACf,OAAO,IAAI,YAAY,CAAC,OAAe,OACrC,KAAK,GAAG,IAAI,QAAQ,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,GAAK,QAAQ,MAAM,OAAO,KAAI;AAEzE;;;CAGC,GACD,OAAO,IAAI,QAAQ,IAAG;AAEtB;;;;;CAKC,GACD,OAAO,IAAI,UAAU,CACnB,OACA,OACA,MACA,QAAQ,KAAK;EAEb,IAAI;EACJ,KAAK,IAAI,KAAK,MAAO;IACnB,IAAI,IAAI,KAAK;IACb,IAAI,CAAC,GAAG;IACR,IAAI,MAAM,UAAU,OAAO;IAC3B,IAAI,OAAO,SAAS,CAAC,CAAC,QAAQ,MAAM,IAAI,CAAC,EAAE,GAAG,OAAO;MAAC;MAAG;KAAI;EAC/D;EACA,OAAO,MAAM,CAAC,EAAE;AAClB,EAAC"}
package/match.ts ADDED
@@ -0,0 +1,118 @@
1
+ // Matching a name someone typed against the names available. Nobody types a
2
+ // name exactly as it is stored — the case drifts, the punctuation is dropped, a
3
+ // long name gets abbreviated to its first word — so an exact string comparison
4
+ // returns "no such author" far too often.
5
+ //
6
+ // This is scoring only. Which entities are addressable by name, and which
7
+ // property holds the name, is names.ts; what to do with the winner is up to the
8
+ // caller.
9
+
10
+ // Two names are compared with both stripped: case, spaces and punctuation carry
11
+ // no meaning in a typed name ('le-guin' and 'Le Guin' find the same entity).
12
+ let norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '')
13
+
14
+ // What two names share at either end costs no edit, so only the middle between
15
+ // is measured: `harnes` against `harness` is one insertion, found without a
16
+ // table.
17
+ let middle = (a: string, b: string): [string, string] => {
18
+ let i = 0
19
+ while (i < a.length && i < b.length && a[i] == b[i]) i++
20
+ let j = 0
21
+ while (
22
+ j < a.length - i && j < b.length - i &&
23
+ a[a.length - 1 - j] == b[b.length - 1 - j]
24
+ ) j++
25
+ return [a.slice(i, a.length - j), b.slice(i, b.length - j)]
26
+ }
27
+
28
+ // Levenshtein distance, one row at a time — over a single name, so the naive
29
+ // table is the right size.
30
+ let dist = (x: string, y: string) => {
31
+ let [a, b] = middle(x, y)
32
+ if (!a || !b) return a.length + b.length
33
+ let row: number[] = []
34
+ for (let j = 0; j <= b.length; j++) row.push(j)
35
+ for (let i = 1; i <= a.length; i++) {
36
+ let prev = row[0]
37
+ row[0] = i
38
+ for (let j = 1; j <= b.length; j++) {
39
+ let swap = row[j]
40
+ row[j] = Math.min(
41
+ row[j] + 1,
42
+ row[j - 1] + 1,
43
+ prev + (a[i - 1] == b[j - 1] ? 0 : 1),
44
+ )
45
+ prev = swap
46
+ }
47
+ }
48
+ return row[b.length]
49
+ }
50
+
51
+ // What a substring match is worth, and 0 when there is none. It earns its place
52
+ // because edit distance alone treats a longer name as unrelated — `earthsea`
53
+ // against `A Wizard of Earthsea` scores close to nothing. Two conditions keep it
54
+ // from firing on coincidence: the shorter string must cover most of the longer
55
+ // one (otherwise `le` is inside half the shelf), and a prefix scores higher than
56
+ // a substring appearing anywhere else, because a prefix is how a name usually
57
+ // gets abbreviated.
58
+ let within = (a: string, b: string) => {
59
+ let [small, big] = a.length < b.length ? [a, b] : [b, a]
60
+ if (small.length < 3 || !big.includes(small)) return 0
61
+ if (small.length * 2 < big.length) return 0
62
+ return big.startsWith(small) ? 0.9 : 0.7
63
+ }
64
+
65
+ /**
66
+ * How close a typed word is to a name, from 0 (nothing) to 1 (the same name).
67
+ * Both sides are normalized first, so case and punctuation never decide.
68
+ */
69
+ export let score = (typed: string, name: string): number => {
70
+ let [a, b] = [norm(typed), norm(name)]
71
+ return !a || !b ? 0 : a == b ? 1 : within(a, b) ||
72
+ 1 - dist(a, b) / Math.max(a.length, b.length)
73
+ }
74
+
75
+ /**
76
+ * The strings a candidate can be matched by, and what each is worth: the whole
77
+ * name, and its first word — which is how a name gets shortened
78
+ * (`Ursula Le Guin` → `ursula`). Words in the middle are excluded: scoring them
79
+ * would let a common word buried in a long name win outright, and in a large
80
+ * store there is always such a word.
81
+ */
82
+ export let answers = (name: string): [string, number][] => [
83
+ [name, 1],
84
+ [name.split(/\s+/)[0] ?? '', 0.85],
85
+ ]
86
+
87
+ /** How close a typed word is to a candidate, across every string it can be
88
+ * matched by. */
89
+ export let closeness = (typed: string, name: string): number =>
90
+ Math.max(...answers(name).map(([w, worth]) => worth * score(typed, w)))
91
+
92
+ /**
93
+ * The score at which a match is close enough to be the name that was intended.
94
+ * Below this, a guess is noise, and returning nothing is more useful.
95
+ */
96
+ export let CLOSE = 0.6
97
+
98
+ /**
99
+ * The candidate whose name is closest to what was typed, or nothing when none
100
+ * is close enough. `name` reads a candidate's name (a candidate with none is
101
+ * skipped); `close` is the threshold the winner must clear — pass 1 to accept
102
+ * exact names only.
103
+ */
104
+ export let nearest = <T>(
105
+ typed: string,
106
+ among: T[],
107
+ name: (x: T) => string | undefined,
108
+ close = CLOSE,
109
+ ): T | undefined => {
110
+ let best: [T, number] | undefined
111
+ for (let x of among) {
112
+ let n = name(x)
113
+ if (!n) continue
114
+ let hit = closeness(typed, n)
115
+ if (hit >= close && (!best || hit > best[1])) best = [x, hit]
116
+ }
117
+ return best?.[0]
118
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://yak.sh/vocab/names",
4
+ "title": "yaks names keyword vocabulary",
5
+ "description": "The keyword @yaks/names adds to a component vocabulary. A component declaring `by_name` makes its entities addressable by the name a person types — an author is found by typing \"Ursula Le Guin\", whereas a review is not found by the sentence it opens with.",
6
+ "$comment": "A vocabulary declaration in the JSON Schema sense: a URI naming this keyword set, plus the schema of each keyword. A vocab file declares it under $vocabulary; a loader registers it with loadVocab(docs, [nameKeywords]).",
7
+ "$defs": {
8
+ "by_name": {
9
+ "description": "true = this component's entities are addressable by name, read from the vocabulary's default name property (`doc.title`). A string names a different property, with its component: \"by_name\": \"shelf.label\" reads the name from `shelf.label`.",
10
+ "anyOf": [{ "type": "boolean" }, { "type": "string" }]
11
+ }
12
+ }
13
+ }
package/mod.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @yaks/names — resolve an entity by name.
3
+ *
4
+ * ## Not everything has a name
5
+ * An author is found by typing `Ursula Le Guin`. A review is not found by the
6
+ * sentence it opens with, even though it has a title too: a word buried in a
7
+ * store's prose matches by coincidence, and in a large store there is always
8
+ * one such word. So each component declares which case it is.
9
+ *
10
+ * ## The `by_name` keyword This package owns one keyword. A component that
11
+ * declares `"by_name": true` makes its entities addressable by name, read from
12
+ * the vocabulary's name property (`doc.title` by default); a string names a
13
+ * different property, with its component (`"by_name": "shelf.label"`).
14
+ *
15
+ * ```json
16
+ * { "$defs": { "author": { "type": "object", "kind": true, "by_name": true } } }
17
+ * ```
18
+ *
19
+ * Register it when you load the vocabulary, and names resolve:
20
+ *
21
+ * ```ts
22
+ * import { loadVocab } from '@yaks/vocab'
23
+ * import { docDoc } from '@yaks/doc'
24
+ * import { nameKeywords, named, nameOf, resolve } from '@yaks/names'
25
+ *
26
+ * let catalog = {
27
+ * $defs: {
28
+ * author: { component: true, kind: true, by_name: true },
29
+ * review: { component: true, kind: true },
30
+ * },
31
+ * }
32
+ * let v = loadVocab([docDoc, catalog], [nameKeywords])
33
+ * let shelf = [
34
+ * { comps: { author: {}, doc: { title: 'Ursula Le Guin' } } },
35
+ * { comps: { review: {}, doc: { title: 'Ursula at her best' } } },
36
+ * ]
37
+ *
38
+ * named(v) // { author: { comp: 'doc', prop: 'title' } }
39
+ * nameOf(v)(shelf[0]) // 'Ursula Le Guin'
40
+ * nameOf(v)(shelf[1]) // undefined — a review's title is not a name
41
+ * resolve(v)('le guin', shelf) // the author
42
+ * ```
43
+ *
44
+ * An exact name always wins; failing that, the closest name above the match
45
+ * threshold does, because nobody types a name exactly as it is stored — the
46
+ * case drifts, the punctuation is dropped, a long name gets abbreviated to its
47
+ * first word. Pass `{ close: 1 }` to accept exact names only.
48
+ *
49
+ * The pieces:
50
+ * - `keywords.ts` — the `by_name` keyword vocabulary, ready to register
51
+ * - `names.ts` — what the vocabulary declares: which components are addressable
52
+ * by name, which property holds the name, and which entity a typed name
53
+ * refers to
54
+ * - `match.ts` — the scoring, on its own: how close two names are
55
+ *
56
+ * @module
57
+ */ export * from "./keywords.js";
58
+ export * from "./match.js";
59
+ export * from "./names.js";
60
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDC,GAED,8BAA6B;AAC7B,2BAA0B;AAC1B,2BAA0B"}
package/mod.ts ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @yaks/names — resolve an entity by name.
3
+ *
4
+ * ## Not everything has a name
5
+ * An author is found by typing `Ursula Le Guin`. A review is not found by the
6
+ * sentence it opens with, even though it has a title too: a word buried in a
7
+ * store's prose matches by coincidence, and in a large store there is always
8
+ * one such word. So each component declares which case it is.
9
+ *
10
+ * ## The `by_name` keyword This package owns one keyword. A component that
11
+ * declares `"by_name": true` makes its entities addressable by name, read from
12
+ * the vocabulary's name property (`doc.title` by default); a string names a
13
+ * different property, with its component (`"by_name": "shelf.label"`).
14
+ *
15
+ * ```json
16
+ * { "$defs": { "author": { "type": "object", "kind": true, "by_name": true } } }
17
+ * ```
18
+ *
19
+ * Register it when you load the vocabulary, and names resolve:
20
+ *
21
+ * ```ts
22
+ * import { loadVocab } from '@yaks/vocab'
23
+ * import { docDoc } from '@yaks/doc'
24
+ * import { nameKeywords, named, nameOf, resolve } from '@yaks/names'
25
+ *
26
+ * let catalog = {
27
+ * $defs: {
28
+ * author: { component: true, kind: true, by_name: true },
29
+ * review: { component: true, kind: true },
30
+ * },
31
+ * }
32
+ * let v = loadVocab([docDoc, catalog], [nameKeywords])
33
+ * let shelf = [
34
+ * { comps: { author: {}, doc: { title: 'Ursula Le Guin' } } },
35
+ * { comps: { review: {}, doc: { title: 'Ursula at her best' } } },
36
+ * ]
37
+ *
38
+ * named(v) // { author: { comp: 'doc', prop: 'title' } }
39
+ * nameOf(v)(shelf[0]) // 'Ursula Le Guin'
40
+ * nameOf(v)(shelf[1]) // undefined — a review's title is not a name
41
+ * resolve(v)('le guin', shelf) // the author
42
+ * ```
43
+ *
44
+ * An exact name always wins; failing that, the closest name above the match
45
+ * threshold does, because nobody types a name exactly as it is stored — the
46
+ * case drifts, the punctuation is dropped, a long name gets abbreviated to its
47
+ * first word. Pass `{ close: 1 }` to accept exact names only.
48
+ *
49
+ * The pieces:
50
+ * - `keywords.ts` — the `by_name` keyword vocabulary, ready to register
51
+ * - `names.ts` — what the vocabulary declares: which components are addressable
52
+ * by name, which property holds the name, and which entity a typed name
53
+ * refers to
54
+ * - `match.ts` — the scoring, on its own: how close two names are
55
+ *
56
+ * @module
57
+ */
58
+
59
+ export * from './keywords.js'
60
+ export * from './match.js'
61
+ export * from './names.js'
package/names.js ADDED
@@ -0,0 +1,69 @@
1
+ // The `by_name` keyword, interpreted: which components are addressable by name,
2
+ // which property holds that name, and which entity a typed name refers to.
3
+ //
4
+ // Not every entity has a name. An author is found by typing `Ursula Le Guin`; a
5
+ // review is not found by the sentence it opens with, even though it has a title
6
+ // too — a title buried in a store's prose matches by coincidence, and there is
7
+ // always one such title. So a component declares it: `by_name`. Everything here
8
+ // reads that declaration off a loaded vocabulary; nothing is hardcoded.
9
+ import { CLOSE, nearest } from "./match.js";
10
+ // A component's declaration → the property its name is held in. `true` uses the
11
+ // vocabulary's default name property; a string names another, with its
12
+ // component (`shelf.label`). Anything else (absent, false) means this
13
+ // component's entities have no name.
14
+ let holder = (v, said, prop)=>{
15
+ if (said !== true && typeof said != 'string') return undefined;
16
+ let path = said === true ? prop : said;
17
+ // aim() throws for a property the vocabulary does not declare — the caller
18
+ // asked for names from a property that is not there, and returning nothing
19
+ // would instead read as "no component is addressable by name".
20
+ let [hop, ...more] = v.aim(path);
21
+ if (more.length || !hop.prop) {
22
+ throw new Error(`a name is one property, as comp.prop: ${path}`);
23
+ }
24
+ return hop;
25
+ };
26
+ /**
27
+ * Every component addressable by name, mapped to the property holding it:
28
+ * `{ author: { comp: 'doc', prop: 'title' } }`. Reads the `by_name` keyword, so
29
+ * the vocabulary must have been loaded with `nameKeywords` registered — an
30
+ * unregistered keyword is invisible to the loader.
31
+ */ export let named = (v, opts = {})=>{
32
+ let out = {};
33
+ for (let name of v.all){
34
+ let hop = holder(v, v.comp(name)?.keywords.by_name, opts.prop ?? 'doc.title');
35
+ if (hop) out[name] = hop;
36
+ }
37
+ return out;
38
+ };
39
+ /**
40
+ * An entity's name, or nothing when it has none. Config-first over a loaded
41
+ * vocabulary: `let name = nameOf(v)`, then `name(author)`. An entity has a name
42
+ * when it carries a component declared `by_name` and the property that
43
+ * declaration points at holds a string — so the same `doc.title` is a name on
44
+ * an author and merely text on a review.
45
+ */ export let nameOf = (v, opts = {})=>{
46
+ let table = named(v, opts);
47
+ return (e)=>{
48
+ for (let [comp, at] of Object.entries(table)){
49
+ if (!e.comps[comp]) continue;
50
+ let value = e.comps[at.comp]?.[at.prop];
51
+ if (typeof value == 'string' && value) return value;
52
+ }
53
+ return undefined;
54
+ };
55
+ };
56
+ /**
57
+ * The entity a typed name refers to, or nothing when none is close enough.
58
+ * Config-first: `let byName = resolve(v)`, then `byName('le guin', authors)`.
59
+ *
60
+ * An exact name always wins. Failing that, the closest name above the match
61
+ * threshold wins, because nobody types a name exactly as it is stored — pass
62
+ * `{ close: 1 }` for exact names only. Candidates with no name are skipped, so
63
+ * a store's prose can never be matched by a word inside it.
64
+ */ export let resolve = (v, opts = {})=>{
65
+ let name = nameOf(v, opts);
66
+ let close = opts.close ?? CLOSE;
67
+ return (typed, among)=>nearest(typed, among, name, close);
68
+ };
69
+ //# sourceMappingURL=names.js.map
package/names.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"names.js","sources":["./names.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,2EAA2E;AAC3E,EAAE;AACF,gFAAgF;AAChF,gFAAgF;AAChF,+EAA+E;AAC/E,gFAAgF;AAChF,wEAAwE;AAGxE,SAAS,KAAK,EAAE,OAAO,qBAAoB;AAe3C,gFAAgF;AAChF,uEAAuE;AACvE,sEAAsE;AACtE,qCAAqC;AACrC,IAAI,SAAS,CAAC,GAAU,MAAe;EACrC,IAAI,SAAS,QAAQ,OAAO,QAAQ,UAAU,OAAO;EACrD,IAAI,OAAO,SAAS,OAAO,OAAO;EAClC,2EAA2E;EAC3E,2EAA2E;EAC3E,+DAA+D;EAC/D,IAAI,CAAC,KAAK,GAAG,KAAK,GAAG,EAAE,GAAG,CAAC;EAC3B,IAAI,KAAK,MAAM,IAAI,CAAC,IAAI,IAAI,EAAE;IAC5B,MAAM,IAAI,MAAM,CAAC,sCAAsC,EAAE,MAAM;EACjE;EACA,OAAO;AACT;AAEA;;;;;CAKC,GACD,OAAO,IAAI,QAAQ,CAAC,GAAU,OAAa,CAAC,CAAC;EAC3C,IAAI,MAA2B,CAAC;EAChC,KAAK,IAAI,QAAQ,EAAE,GAAG,CAAE;IACtB,IAAI,MAAM,OACR,GACA,EAAE,IAAI,CAAC,OAAO,SAAS,SACvB,KAAK,IAAI,IAAI;IAEf,IAAI,KAAK,GAAG,CAAC,KAAK,GAAG;EACvB;EACA,OAAO;AACT,EAAC;AAED;;;;;;CAMC,GACD,OAAO,IAAI,SAAS,CAClB,GACA,OAAa,CAAC,CAAC;EAEf,IAAI,QAAQ,MAAM,GAAG;EACrB,OAAO,CAAC;IACN,KAAK,IAAI,CAAC,MAAM,GAAG,IAAI,OAAO,OAAO,CAAC,OAAQ;MAC5C,IAAI,CAAC,EAAE,KAAK,CAAC,KAAK,EAAE;MACpB,IAAI,QAAQ,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC;MACvC,IAAI,OAAO,SAAS,YAAY,OAAO,OAAO;IAChD;IACA,OAAO;EACT;AACF,EAAC;AAED;;;;;;;;CAQC,GACD,OAAO,IAAI,UAAU,CACnB,GACA,OAAa,CAAC,CAAC;EAEf,IAAI,OAAO,OAAO,GAAG;EACrB,IAAI,QAAQ,KAAK,KAAK,IAAI;EAC1B,OAAO,CAAC,OAAO,QAAU,QAAQ,OAAO,OAAO,MAAM;AACvD,EAAC"}
package/names.ts ADDED
@@ -0,0 +1,100 @@
1
+ // The `by_name` keyword, interpreted: which components are addressable by name,
2
+ // which property holds that name, and which entity a typed name refers to.
3
+ //
4
+ // Not every entity has a name. An author is found by typing `Ursula Le Guin`; a
5
+ // review is not found by the sentence it opens with, even though it has a title
6
+ // too — a title buried in a store's prose matches by coincidence, and there is
7
+ // always one such title. So a component declares it: `by_name`. Everything here
8
+ // reads that declaration off a loaded vocabulary; nothing is hardcoded.
9
+
10
+ import type { Hop, Vocab } from 'jsr:@yaks/vocab@0.2.36'
11
+ import { CLOSE, nearest } from './match.js'
12
+
13
+ /** An entity as this package reads it: component name → that component's
14
+ * properties. Any other fields are left untouched, so a caller's own row type
15
+ * works as long as its components are under `comps`. */
16
+ export type Comps = Record<string, Record<string, unknown> | undefined>
17
+
18
+ /** The shape a candidate must have to be resolved: the components it carries. */
19
+ export type Carried = { comps: Comps }
20
+
21
+ /** How names are read: `prop` is the default name property, named with its
22
+ * component (`doc.title` unless said), and `close` is the match threshold — 1
23
+ * accepts exact names only. */
24
+ export type Opts = { prop?: string; close?: number }
25
+
26
+ // A component's declaration → the property its name is held in. `true` uses the
27
+ // vocabulary's default name property; a string names another, with its
28
+ // component (`shelf.label`). Anything else (absent, false) means this
29
+ // component's entities have no name.
30
+ let holder = (v: Vocab, said: unknown, prop: string): Hop | undefined => {
31
+ if (said !== true && typeof said != 'string') return undefined
32
+ let path = said === true ? prop : said
33
+ // aim() throws for a property the vocabulary does not declare — the caller
34
+ // asked for names from a property that is not there, and returning nothing
35
+ // would instead read as "no component is addressable by name".
36
+ let [hop, ...more] = v.aim(path)
37
+ if (more.length || !hop.prop) {
38
+ throw new Error(`a name is one property, as comp.prop: ${path}`)
39
+ }
40
+ return hop
41
+ }
42
+
43
+ /**
44
+ * Every component addressable by name, mapped to the property holding it:
45
+ * `{ author: { comp: 'doc', prop: 'title' } }`. Reads the `by_name` keyword, so
46
+ * the vocabulary must have been loaded with `nameKeywords` registered — an
47
+ * unregistered keyword is invisible to the loader.
48
+ */
49
+ export let named = (v: Vocab, opts: Opts = {}): Record<string, Hop> => {
50
+ let out: Record<string, Hop> = {}
51
+ for (let name of v.all) {
52
+ let hop = holder(
53
+ v,
54
+ v.comp(name)?.keywords.by_name,
55
+ opts.prop ?? 'doc.title',
56
+ )
57
+ if (hop) out[name] = hop
58
+ }
59
+ return out
60
+ }
61
+
62
+ /**
63
+ * An entity's name, or nothing when it has none. Config-first over a loaded
64
+ * vocabulary: `let name = nameOf(v)`, then `name(author)`. An entity has a name
65
+ * when it carries a component declared `by_name` and the property that
66
+ * declaration points at holds a string — so the same `doc.title` is a name on
67
+ * an author and merely text on a review.
68
+ */
69
+ export let nameOf = (
70
+ v: Vocab,
71
+ opts: Opts = {},
72
+ ): (e: Carried) => string | undefined => {
73
+ let table = named(v, opts)
74
+ return (e) => {
75
+ for (let [comp, at] of Object.entries(table)) {
76
+ if (!e.comps[comp]) continue
77
+ let value = e.comps[at.comp]?.[at.prop]
78
+ if (typeof value == 'string' && value) return value
79
+ }
80
+ return undefined
81
+ }
82
+ }
83
+
84
+ /**
85
+ * The entity a typed name refers to, or nothing when none is close enough.
86
+ * Config-first: `let byName = resolve(v)`, then `byName('le guin', authors)`.
87
+ *
88
+ * An exact name always wins. Failing that, the closest name above the match
89
+ * threshold wins, because nobody types a name exactly as it is stored — pass
90
+ * `{ close: 1 }` for exact names only. Candidates with no name are skipped, so
91
+ * a store's prose can never be matched by a word inside it.
92
+ */
93
+ export let resolve = (
94
+ v: Vocab,
95
+ opts: Opts = {},
96
+ ): <T extends Carried>(name: string, among: T[]) => T | undefined => {
97
+ let name = nameOf(v, opts)
98
+ let close = opts.close ?? CLOSE
99
+ return (typed, among) => nearest(typed, among, name, close)
100
+ }
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@yaks/names",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/names",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ }
11
+ },
12
+ "license": "Apache-2.0",
13
+ "dependencies": {
14
+ "@yaks/vocab": "0.2.36"
15
+ },
16
+ "description": "Resolves entity names from the properties a component vocabulary marks for name lookup.",
17
+ "repository": "https://github.com/yak-sh/yak.git"
18
+ }