@yaks/copy 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/locales.js ADDED
@@ -0,0 +1,211 @@
1
+ // Language selection and translation provenance for an app's copy files.
2
+ import { keys, same, slots, valueAt, withCopy } from "./mod.js";
3
+ export let COPY = 'copy.json';
4
+ export let LOCALES = 'copy.locale.json';
5
+ export let LANGUAGE = 'lang';
6
+ export let LANGUAGES = 'x-yak-copy-languages';
7
+ /** A language tag in the form used by HTML and by the locale file names. */ export let language = (tag)=>{
8
+ if (typeof tag != 'string' || !/^[a-z\d-]{1,90}$/i.test(tag)) return;
9
+ try {
10
+ return Intl.getCanonicalLocales(tag)[0];
11
+ } catch {
12
+ return;
13
+ }
14
+ };
15
+ export let localeFile = (lang)=>`copy.${lang}.json`;
16
+ export let copyLanguage = (path)=>path == LOCALES ? undefined : language(/^copy\.([^/]+)\.json$/.exec(path)?.[1]);
17
+ export let isCopyFile = (path)=>path == COPY || path == LOCALES || !!copyLanguage(path);
18
+ let object = (value)=>!!value && typeof value == 'object' && !Array.isArray(value);
19
+ let value = (item)=>typeof item == 'string' || Array.isArray(item) && item.every((part)=>typeof part == 'string');
20
+ /** The app's language settings and the sources used by its translations. */ export let locales = (text)=>{
21
+ if (!text.trim()) return null;
22
+ let raw = JSON.parse(text);
23
+ let base = object(raw) && language(raw.default);
24
+ if (!base || !object(raw) || !object(raw.languages)) {
25
+ throw new Error(`${LOCALES} needs a default language and a languages object`);
26
+ }
27
+ let entries = Object.entries(raw.languages).map(([name, held])=>{
28
+ let tag = language(name);
29
+ if (!tag || name != tag || tag == base || localeFile(tag) == LOCALES || !object(held)) {
30
+ throw new Error(`${LOCALES} has an invalid language: ${name}`);
31
+ }
32
+ let sources = Object.fromEntries(Object.entries(object(held.sources) ? held.sources : {}).flatMap(([key, origin])=>object(origin) && value(origin.source) ? [
33
+ [
34
+ key,
35
+ {
36
+ source: origin.source,
37
+ ...origin.human === true ? {
38
+ human: true
39
+ } : {}
40
+ }
41
+ ]
42
+ ] : []));
43
+ let preferences = Array.isArray(held.preferences) ? held.preferences.filter((part)=>typeof part == 'string') : [];
44
+ let label = typeof held.label == 'string' ? held.label.trim() : '';
45
+ return [
46
+ tag,
47
+ {
48
+ ...label ? {
49
+ label
50
+ } : {},
51
+ sources,
52
+ ...preferences.length ? {
53
+ preferences
54
+ } : {}
55
+ }
56
+ ];
57
+ });
58
+ return {
59
+ default: base,
60
+ languages: Object.fromEntries(entries),
61
+ ...raw.suggestions === true ? {
62
+ suggestions: true
63
+ } : {}
64
+ };
65
+ };
66
+ export let languagesOf = (config)=>[
67
+ config.default,
68
+ ...Object.keys(config.languages)
69
+ ];
70
+ // More specific browser tags can use an available parent, or a regional
71
+ // translation when the request only names the parent.
72
+ let lookup = (tag, available)=>{
73
+ for(let name = tag; name; name = name.replace(/-?[^-]+$/, '')){
74
+ let match = available.find((one)=>one == name) ?? available.find((one)=>one.startsWith(name + '-'));
75
+ if (match) return match;
76
+ }
77
+ };
78
+ let preferences = (header)=>header.slice(0, 2048).split(',').map((part)=>{
79
+ let [tag, weight] = part.trim().split(';').map((piece)=>piece.trim());
80
+ return {
81
+ tag: language(tag),
82
+ q: weight ? Number(weight.match(/^q=(.+)$/i)?.[1]) : 1
83
+ };
84
+ }).filter(({ tag, q })=>tag && q > 0 && q <= 1).sort((a, b)=>b.q - a.q);
85
+ /** Choose the address language, remembered choice, browser language, or default. */ export let chooseLanguage = (available, { explicit, remembered, browser = '' } = {})=>{
86
+ if (explicit) {
87
+ let tag = language(explicit);
88
+ if (tag && available.includes(tag)) return tag;
89
+ }
90
+ let choice = language(remembered);
91
+ if (choice && available.includes(choice)) return choice;
92
+ for (let { tag } of preferences(browser)){
93
+ let match = lookup(tag, available);
94
+ if (match) return match;
95
+ }
96
+ return available[0];
97
+ };
98
+ /** An indexed language address on this page. */ export let languageAt = (address, lang)=>{
99
+ let url = new URL(address);
100
+ url.searchParams.set(LANGUAGE, lang);
101
+ return url;
102
+ };
103
+ export let languageCookie = (mount)=>`yak-copy-${encodeURIComponent(mount)}`;
104
+ export let requestLanguage = (req, mount)=>({
105
+ explicit: new URL(req.url).searchParams.get(LANGUAGE),
106
+ remembered: req.headers.get('cookie')?.split(';').map((part)=>part.trim()).find((part)=>part.startsWith(languageCookie(mount) + '='))?.split('=')[1],
107
+ browser: req.headers.get('accept-language') ?? ''
108
+ });
109
+ /** The additional variant needed when the held page uses another language. */ export let copyVariant = (req, headers, mount)=>{
110
+ let available = headers.get(LANGUAGES)?.split(',') ?? [];
111
+ if (available.length < 2) return;
112
+ let tag = chooseLanguage(available, requestLanguage(req, mount));
113
+ if (tag != headers.get('content-language')) return tag;
114
+ };
115
+ /** The default copy with the translated values it has, keeping the source
116
+ * where a translation is missing or has a different shape. */ export let localized = (source, translation)=>withCopy(source, Object.fromEntries(keys(source).flatMap((key)=>{
117
+ let original = valueAt(source, key);
118
+ let translated = valueAt(translation, key);
119
+ return translated !== undefined && compatible(original, translated) ? [
120
+ [
121
+ key,
122
+ translated
123
+ ]
124
+ ] : [];
125
+ })));
126
+ /** Copy slots stay in page order, and a list keeps one translation per item. */ export let compatible = (source, translation)=>{
127
+ if (typeof source == 'string' && typeof translation == 'string') {
128
+ return same(slots(source), slots(translation));
129
+ }
130
+ return Array.isArray(source) && Array.isArray(translation) && source.length == translation.length && source.every((part, index)=>compatible(part, translation[index]));
131
+ };
132
+ /** Keep translations of the current source, including human corrections.
133
+ * A translation with no recorded source is associated with the previous
134
+ * source when available, so an edit to that source still marks it stale. */ export let translationPlan = (source, translated, origins = {}, previous = source)=>{
135
+ let current = [];
136
+ let pending = [];
137
+ let sources = [];
138
+ for (let key of keys(source)){
139
+ let original = valueAt(source, key);
140
+ let words = valueAt(translated, key);
141
+ let from = Object.hasOwn(origins, key) ? origins[key] : {
142
+ source: valueAt(previous, key) ?? original,
143
+ human: true
144
+ };
145
+ if (words === undefined || !same(original, from.source) || !compatible(original, words)) {
146
+ pending.push([
147
+ key,
148
+ original
149
+ ]);
150
+ } else {
151
+ current.push([
152
+ key,
153
+ words
154
+ ]);
155
+ sources.push([
156
+ key,
157
+ from
158
+ ]);
159
+ }
160
+ }
161
+ return {
162
+ current: Object.fromEntries(current),
163
+ pending: Object.fromEntries(pending),
164
+ sources: Object.fromEntries(sources)
165
+ };
166
+ };
167
+ /** Apply a model answer only to the keys in the plan. */ export let translated = (plan, answer)=>{
168
+ let current = {
169
+ ...plan.current
170
+ };
171
+ let sources = {
172
+ ...plan.sources
173
+ };
174
+ for (let [key, original] of Object.entries(plan.pending)){
175
+ let words = valueAt(answer, key);
176
+ if (words === undefined || !compatible(original, words)) {
177
+ throw new Error(`Translation has the wrong shape for ${key}`);
178
+ }
179
+ Object.defineProperty(current, key, {
180
+ value: words,
181
+ enumerable: true
182
+ });
183
+ Object.defineProperty(sources, key, {
184
+ value: {
185
+ source: original
186
+ },
187
+ enumerable: true
188
+ });
189
+ }
190
+ return {
191
+ current,
192
+ sources
193
+ };
194
+ };
195
+ /** Snippets much longer than the source, for the editor's phone-width check. */ export let longTranslations = (source, translation)=>{
196
+ let wide = (from, to)=>[
197
+ ...to
198
+ ].length > Math.max([
199
+ ...from
200
+ ].length * 1.3, [
201
+ ...from
202
+ ].length + 8);
203
+ return Object.entries(source).flatMap(([key, from])=>{
204
+ let to = valueAt(translation, key);
205
+ let long = typeof from == 'string' && typeof to == 'string' ? wide(from, to) : Array.isArray(from) && Array.isArray(to) && from.some((part, index)=>wide(part, to[index] ?? ''));
206
+ return long ? [
207
+ key
208
+ ] : [];
209
+ });
210
+ };
211
+ //# sourceMappingURL=locales.js.map
package/locales.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"locales.js","sources":["./locales.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,SAEE,IAAI,EACJ,IAAI,EACJ,KAAK,EAEL,OAAO,EACP,QAAQ,mBACO;AAEjB,OAAO,IAAI,OAAO,YAAW;AAC7B,OAA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E,QAAQ;MAAS;MAC1B,YAAY;IACd;EACF;EACA,OAAO;IAAE;IAAS;EAAQ;AAC5B,EAAC;AAED,8EAA8E,GAC9E,OAAO,IAAI,mBAAmB,CAC5B,QACA;EAEA,IAAI,OAAO,CAAC,MAAc,KACxB;SAAI;KAAG,CAAC,MAAM,GAAG,KAAK,GAAG,CAAC;SAAI;KAAK,CAAC,MAAM,GAAG,KAAK;SAAI;KAAK,CAAC,MAAM,GAAG;EACvE,OAAO,OAAO,OAAO,CAAC,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,KAAK;IAChD,IAAI,KAAK,QAAQ,aAAa;IAC9B,IAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,MAAM,WAC/C,KAAK,MAAM,MACX,MAAM,OAAO,CAAC,SAAS,MAAM,OAAO,CAAC,OACrC,KAAK,IAAI,CAAC,CAAC,MAAM,QAAU,KAAK,MAAM,EAAE,CAAC,MAAM,IAAI;IACvD,OAAO,OAAO;MAAC;KAAI,GAAG,EAAE;EAC1B;AACF,EAAC"}
package/locales.ts ADDED
@@ -0,0 +1,292 @@
1
+ // Language selection and translation provenance for an app's copy files.
2
+ import {
3
+ type Copy,
4
+ keys,
5
+ same,
6
+ slots,
7
+ type Value,
8
+ valueAt,
9
+ withCopy,
10
+ } from './mod.js'
11
+
12
+ export let COPY = 'copy.json'
13
+ export let LOCALES = 'copy.locale.json'
14
+ export let LANGUAGE = 'lang'
15
+ export let LANGUAGES = 'x-yak-copy-languages'
16
+
17
+ /** A language tag in the form used by HTML and by the locale file names. */
18
+ export let language = (tag: unknown): string | undefined => {
19
+ if (typeof tag != 'string' || !/^[a-z\d-]{1,90}$/i.test(tag)) return
20
+ try {
21
+ return Intl.getCanonicalLocales(tag)[0]
22
+ } catch {
23
+ return
24
+ }
25
+ }
26
+
27
+ export let localeFile = (lang: string) => `copy.${lang}.json`
28
+
29
+ export let copyLanguage = (path: string): string | undefined =>
30
+ path == LOCALES
31
+ ? undefined
32
+ : language(/^copy\.([^/]+)\.json$/.exec(path)?.[1])
33
+
34
+ export let isCopyFile = (path: string): boolean =>
35
+ path == COPY || path == LOCALES || !!copyLanguage(path)
36
+
37
+ export type Snippets = Record<string, Value>
38
+ export type Origin = { source: Value; human?: boolean }
39
+ export type Locale = {
40
+ label?: string
41
+ sources?: Record<string, Origin>
42
+ preferences?: string[]
43
+ }
44
+ export type Locales = {
45
+ default: string
46
+ languages: Record<string, Locale>
47
+ suggestions?: boolean
48
+ }
49
+
50
+ let object = (value: unknown): value is Record<string, unknown> =>
51
+ !!value && typeof value == 'object' && !Array.isArray(value)
52
+ let value = (item: unknown): item is Value =>
53
+ typeof item == 'string' ||
54
+ Array.isArray(item) && item.every((part) => typeof part == 'string')
55
+
56
+ /** The app's language settings and the sources used by its translations. */
57
+ export let locales = (text: string): Locales | null => {
58
+ if (!text.trim()) return null
59
+ let raw: unknown = JSON.parse(text)
60
+ let base = object(raw) && language(raw.default)
61
+ if (!base || !object(raw) || !object(raw.languages)) {
62
+ throw new Error(
63
+ `${LOCALES} needs a default language and a languages object`,
64
+ )
65
+ }
66
+ let entries = Object.entries(raw.languages).map(([name, held]) => {
67
+ let tag = language(name)
68
+ if (
69
+ !tag || name != tag || tag == base || localeFile(tag) == LOCALES ||
70
+ !object(held)
71
+ ) {
72
+ throw new Error(`${LOCALES} has an invalid language: ${name}`)
73
+ }
74
+ let sources = Object.fromEntries(
75
+ Object.entries(object(held.sources) ? held.sources : {}).flatMap(
76
+ ([key, origin]) =>
77
+ object(origin) && value(origin.source)
78
+ ? [[key, {
79
+ source: origin.source,
80
+ ...origin.human === true ? { human: true } : {},
81
+ }]]
82
+ : [],
83
+ ),
84
+ )
85
+ let preferences = Array.isArray(held.preferences)
86
+ ? held.preferences.filter((part): part is string =>
87
+ typeof part == 'string'
88
+ )
89
+ : []
90
+ let label = typeof held.label == 'string' ? held.label.trim() : ''
91
+ return [tag, {
92
+ ...label ? { label } : {},
93
+ sources,
94
+ ...preferences.length ? { preferences } : {},
95
+ }]
96
+ })
97
+ return {
98
+ default: base,
99
+ languages: Object.fromEntries(entries),
100
+ ...raw.suggestions === true ? { suggestions: true } : {},
101
+ }
102
+ }
103
+
104
+ export let languagesOf = (
105
+ config: Locales,
106
+ ): string[] => [config.default, ...Object.keys(config.languages)]
107
+
108
+ // More specific browser tags can use an available parent, or a regional
109
+ // translation when the request only names the parent.
110
+ let lookup = (
111
+ tag: string,
112
+ available: readonly string[],
113
+ ): string | undefined => {
114
+ for (let name = tag; name; name = name.replace(/-?[^-]+$/, '')) {
115
+ let match = available.find((one) => one == name) ??
116
+ available.find((one) => one.startsWith(name + '-'))
117
+ if (match) return match
118
+ }
119
+ }
120
+
121
+ let preferences = (header: string) =>
122
+ header.slice(0, 2048).split(',').map((part) => {
123
+ let [tag, weight] = part.trim().split(';').map((piece) => piece.trim())
124
+ return {
125
+ tag: language(tag),
126
+ q: weight ? Number(weight.match(/^q=(.+)$/i)?.[1]) : 1,
127
+ }
128
+ }).filter(({ tag, q }) => tag && q > 0 && q <= 1).sort((a, b) => b.q - a.q)
129
+
130
+ export type LanguageRequest = {
131
+ explicit?: string | null
132
+ remembered?: string | null
133
+ browser?: string
134
+ }
135
+
136
+ /** Choose the address language, remembered choice, browser language, or default. */
137
+ export let chooseLanguage = (
138
+ available: readonly [string, ...string[]] | readonly string[],
139
+ { explicit, remembered, browser = '' }: LanguageRequest = {},
140
+ ): string => {
141
+ if (explicit) {
142
+ let tag = language(explicit)
143
+ if (tag && available.includes(tag)) return tag
144
+ }
145
+ let choice = language(remembered)
146
+ if (choice && available.includes(choice)) return choice
147
+ for (let { tag } of preferences(browser)) {
148
+ let match = lookup(tag!, available)
149
+ if (match) return match
150
+ }
151
+ return available[0]
152
+ }
153
+
154
+ /** An indexed language address on this page. */
155
+ export let languageAt = (address: string | URL, lang: string): URL => {
156
+ let url = new URL(address)
157
+ url.searchParams.set(LANGUAGE, lang)
158
+ return url
159
+ }
160
+
161
+ export let languageCookie = (mount: string) =>
162
+ `yak-copy-${encodeURIComponent(mount)}`
163
+
164
+ export let requestLanguage = (
165
+ req: Request,
166
+ mount: string,
167
+ ): LanguageRequest => ({
168
+ explicit: new URL(req.url).searchParams.get(LANGUAGE),
169
+ remembered: req.headers.get('cookie')?.split(';').map((part) => part.trim())
170
+ .find((part) => part.startsWith(languageCookie(mount) + '='))?.split(
171
+ '=',
172
+ )[1],
173
+ browser: req.headers.get('accept-language') ?? '',
174
+ })
175
+
176
+ /** The additional variant needed when the held page uses another language. */
177
+ export let copyVariant = (
178
+ req: Request,
179
+ headers: Headers,
180
+ mount: string,
181
+ ): string | undefined => {
182
+ let available = headers.get(LANGUAGES)?.split(',') ?? []
183
+ if (available.length < 2) return
184
+ let tag = chooseLanguage(available, requestLanguage(req, mount))
185
+ if (tag != headers.get('content-language')) return tag
186
+ }
187
+
188
+ /** The default copy with the translated values it has, keeping the source
189
+ * where a translation is missing or has a different shape. */
190
+ export let localized = (source: Copy, translation: Copy): Copy =>
191
+ withCopy(
192
+ source,
193
+ Object.fromEntries(
194
+ keys(source).flatMap((key) => {
195
+ let original = valueAt(source, key)!
196
+ let translated = valueAt(translation, key)
197
+ return translated !== undefined && compatible(original, translated)
198
+ ? [[key, translated]]
199
+ : []
200
+ }),
201
+ ),
202
+ )
203
+
204
+ /** Copy slots stay in page order, and a list keeps one translation per item. */
205
+ export let compatible = (
206
+ source: Value,
207
+ translation: Value | undefined,
208
+ ): boolean => {
209
+ if (typeof source == 'string' && typeof translation == 'string') {
210
+ return same(slots(source), slots(translation))
211
+ }
212
+ return Array.isArray(source) && Array.isArray(translation) &&
213
+ source.length == translation.length &&
214
+ source.every((part, index) => compatible(part, translation[index]))
215
+ }
216
+
217
+ export type Plan = {
218
+ current: Snippets
219
+ pending: Snippets
220
+ sources: Record<string, Origin>
221
+ }
222
+
223
+ /** Keep translations of the current source, including human corrections.
224
+ * A translation with no recorded source is associated with the previous
225
+ * source when available, so an edit to that source still marks it stale. */
226
+ export let translationPlan = (
227
+ source: Copy,
228
+ translated: Copy,
229
+ origins: Record<string, Origin> = {},
230
+ previous: Copy = source,
231
+ ): Plan => {
232
+ let current: [string, Value][] = []
233
+ let pending: [string, Value][] = []
234
+ let sources: [string, Origin][] = []
235
+ for (let key of keys(source)) {
236
+ let original = valueAt(source, key)!
237
+ let words = valueAt(translated, key)
238
+ let from = Object.hasOwn(origins, key) ? origins[key] : {
239
+ source: valueAt(previous, key) ?? original,
240
+ human: true,
241
+ }
242
+ if (
243
+ words === undefined || !same(original, from.source) ||
244
+ !compatible(original, words)
245
+ ) {
246
+ pending.push([key, original])
247
+ } else {
248
+ current.push([key, words])
249
+ sources.push([key, from])
250
+ }
251
+ }
252
+ return {
253
+ current: Object.fromEntries(current),
254
+ pending: Object.fromEntries(pending),
255
+ sources: Object.fromEntries(sources),
256
+ }
257
+ }
258
+
259
+ /** Apply a model answer only to the keys in the plan. */
260
+ export let translated = (plan: Plan, answer: Copy): Omit<Plan, 'pending'> => {
261
+ let current = { ...plan.current }
262
+ let sources = { ...plan.sources }
263
+ for (let [key, original] of Object.entries(plan.pending)) {
264
+ let words = valueAt(answer, key)
265
+ if (words === undefined || !compatible(original, words)) {
266
+ throw new Error(`Translation has the wrong shape for ${key}`)
267
+ }
268
+ Object.defineProperty(current, key, { value: words, enumerable: true })
269
+ Object.defineProperty(sources, key, {
270
+ value: { source: original },
271
+ enumerable: true,
272
+ })
273
+ }
274
+ return { current, sources }
275
+ }
276
+
277
+ /** Snippets much longer than the source, for the editor's phone-width check. */
278
+ export let longTranslations = (
279
+ source: Snippets,
280
+ translation: Copy,
281
+ ): string[] => {
282
+ let wide = (from: string, to: string) =>
283
+ [...to].length > Math.max([...from].length * 1.3, [...from].length + 8)
284
+ return Object.entries(source).flatMap(([key, from]) => {
285
+ let to = valueAt(translation, key)
286
+ let long = typeof from == 'string' && typeof to == 'string'
287
+ ? wide(from, to)
288
+ : Array.isArray(from) && Array.isArray(to) &&
289
+ from.some((part, index) => wide(part, to[index] ?? ''))
290
+ return long ? [key] : []
291
+ })
292
+ }