dsh-cookie-cleaner 0.6.4 → 0.7.2

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.
@@ -1,129 +1,129 @@
1
- /**
2
- * dsh-cookie-cleaner — 浏览器半。
3
- *
4
- * 装载契约(三条都是事故换来的):
5
- * - bundle id 必须 = **npm 包名**(`client/modules/src/index.ts:1040` 用 `graphRow(packageName,…)`),
6
- * 注册 id 与宿主图不一致时 client 半从不加载;
7
- * - 注册必须发生在 apply 顶层:关在任何 inject 回调里的注册两代都会静默失活;
8
- * - 每个面单独 `safe()`:未知槽名在个别宿主线上同步抛错,而 cordis 会吞掉 inject 回调的
9
- * 异常,一个面失败会带走同一回调里的其它面。
10
- *
11
- * `configForms`(0.1.7+)/`settingsScope`(≤0.1.5)是代际互斥服务,绝不写进插件级 inject——
12
- * 那会让整个 client fiber 在另一代上停在 pending。这里只依赖 `slots` + `locale`(三代齐)。
13
- */
14
- import { dictionaries, NS, UI_KEYS } from './locales'
15
- import { PatchCard } from './card'
16
-
17
- /** 宿主 locale 服务的最小面(不引宿主类型包:client bundle 只按运行时形状用)。 */
18
- interface LocaleService {
19
- register(ns: string, dicts: Record<string, Record<string, string>>): unknown
20
- bind?(ns: string): (key: string) => string
21
- on?(event: string, listener: () => void): unknown
22
- }
23
-
24
- interface SlotEntry {
25
- name: string
26
- id?: string
27
- /** keyed 槽必填(`ui-slots/src/index.ts:1222`:缺 key 直接 throw)。 */
28
- key?: string
29
- order?: number
30
- label?: () => string
31
- locale?: string
32
- inject?: () => Record<string, unknown>
33
- }
34
-
35
- interface SlotsService {
36
- inject(name: string, factory: () => Generator<unknown, void, unknown>): unknown
37
- register(entry: SlotEntry, component: unknown): unknown
38
- }
39
-
40
- interface ClientContext {
41
- get?(name: string): unknown
42
- inject(deps: readonly string[], fn: (ctx: ClientContext) => void): unknown
43
- effect(fn: () => unknown, label?: string): unknown
44
- slots?: SlotsService
45
- locale?: LocaleService
46
- }
47
-
48
- /** 插件级 inject 只声明三代都存在的服务。 */
49
- export const inject = ['slots', 'locale'] as const
50
-
51
- /** 当前语言的取词函数(注册后由 locale 服务提供;拿不到 bind 时回落 zh 字典)。 */
52
- let currentT: (key: string) => string = (key) => {
53
- const zh = (dictionaries as Record<string, Record<string, string>>).zh
54
- return zh[key] ?? key
55
- }
56
-
57
- /** 每个面的独立 try/catch:一面抛错不带走其它面。 */
58
- function safe(ctx: ClientContext, tag: string, fn: () => void): void {
59
- try {
60
- fn()
61
- } catch (error) {
62
- // 农场/真机拿不到 console 时也要留痕:失败面写进 window,供探针直接读取。
63
- const surface = ((globalThis as Record<string, unknown>).__dccSurf ??= []) as string[]
64
- surface.push(`${tag}: ${String((error as Error)?.message ?? error)}`)
65
- const logger = typeof ctx.get === 'function' ? ctx.get('logger') as { warn?(msg: string): void } : undefined
66
- if (typeof logger?.warn === 'function') logger.warn(`[dsh-cookie-cleaner] ${tag} failed: ${String((error as Error)?.message ?? error)}`)
67
- }
68
- }
69
-
70
- /**
71
- * 浏览器半入口。
72
- * @param ctx client context。
73
- */
74
- export function apply(ctx: ClientContext): void {
75
- // 字典注册:一次调用带 9 语(map 式注册要求宿主 locale 服务接受任意语言码)。
76
- safe(ctx, 'locale.register', () => {
77
- if (typeof ctx.locale?.register !== 'function') throw new Error('locale service unavailable')
78
- ctx.locale.register(NS, dictionaries)
79
- const bind = ctx.locale.bind?.(NS)
80
- if (typeof bind === 'function') {
81
- // bind 是活的取值器:换语言后重渲染即跟上新值,卡片不自存语言副本。
82
- currentT = (key: string) => bind(key)
83
- }
84
- })
85
-
86
- // 席位 A:设置页顶级独立节(范式 A,不参与家族 tab 选举)。
87
- safe(ctx, 'settings.section', () => {
88
- const slots = ctx.slots
89
- if (slots?.inject === undefined || slots.register === undefined) throw new Error('slots service unavailable')
90
- slots.inject('settings.section', function* () {
91
- yield slots.register({
92
- name: 'settings.section',
93
- id: NS,
94
- order: 45,
95
- label: () => currentT('section.title'),
96
- locale: NS,
97
- inject: () => ({ t: (key: string) => currentT(key) }),
98
- }, PatchCard)
99
- })
100
- })
101
-
102
- // 席位 B:插件页配置卡(0.2.x 上「导出 Config 自动出表单」不成立,必须显式挂)。
103
- // 这个槽是 **keyed** 形态,key = bundle 的包名(真机报错:keyed slot requires options.key)。
104
- safe(ctx, 'plugins.bundle.config', () => {
105
- const slots = ctx.slots
106
- if (slots?.inject === undefined || slots.register === undefined) throw new Error('slots service unavailable')
107
- slots.inject('plugins.bundle.config', function* () {
108
- yield slots.register({
109
- name: 'plugins.bundle.config',
110
- key: NS,
111
- order: 45,
112
- label: () => currentT('section.title'),
113
- locale: NS,
114
- inject: () => ({ t: (key: string) => currentT(key) }),
115
- }, PatchCard)
116
- })
117
- })
118
-
119
- // 装载自检:键集没注册全就是构建坏了,立刻留痕而不是等用户点开空卡。
120
- safe(ctx, 'dictionary sanity', () => {
121
- const langs = Object.keys(dictionaries)
122
- if (langs.length !== 9) throw new Error(`expected 9 languages, got ${String(langs.length)}`)
123
- const missing = langs.filter((lang) => {
124
- const dict = (dictionaries as Record<string, Record<string, string>>)[lang]
125
- return UI_KEYS.some((key) => typeof dict[key] !== 'string' || dict[key] === '')
126
- })
127
- if (missing.length > 0) throw new Error(`empty keys for ${missing.join(', ')}`)
128
- })
129
- }
1
+ /**
2
+ * dsh-cookie-cleaner — 浏览器半。
3
+ *
4
+ * 装载契约(三条都是事故换来的):
5
+ * - bundle id 必须 = **npm 包名**(`client/modules/src/index.ts:1040` 用 `graphRow(packageName,…)`),
6
+ * 注册 id 与宿主图不一致时 client 半从不加载;
7
+ * - 注册必须发生在 apply 顶层:关在任何 inject 回调里的注册两代都会静默失活;
8
+ * - 每个面单独 `safe()`:未知槽名在个别宿主线上同步抛错,而 cordis 会吞掉 inject 回调的
9
+ * 异常,一个面失败会带走同一回调里的其它面。
10
+ *
11
+ * `configForms`(0.1.7+)/`settingsScope`(≤0.1.5)是代际互斥服务,绝不写进插件级 inject——
12
+ * 那会让整个 client fiber 在另一代上停在 pending。这里只依赖 `slots` + `locale`(三代齐)。
13
+ */
14
+ import { dictionaries, NS, UI_KEYS } from './locales'
15
+ import { PatchCard } from './card'
16
+
17
+ /** 宿主 locale 服务的最小面(不引宿主类型包:client bundle 只按运行时形状用)。 */
18
+ interface LocaleService {
19
+ register(ns: string, dicts: Record<string, Record<string, string>>): unknown
20
+ bind?(ns: string): (key: string) => string
21
+ on?(event: string, listener: () => void): unknown
22
+ }
23
+
24
+ interface SlotEntry {
25
+ name: string
26
+ id?: string
27
+ /** keyed 槽必填(`ui-slots/src/index.ts:1222`:缺 key 直接 throw)。 */
28
+ key?: string
29
+ order?: number
30
+ label?: () => string
31
+ locale?: string
32
+ inject?: () => Record<string, unknown>
33
+ }
34
+
35
+ interface SlotsService {
36
+ inject(name: string, factory: () => Generator<unknown, void, unknown>): unknown
37
+ register(entry: SlotEntry, component: unknown): unknown
38
+ }
39
+
40
+ interface ClientContext {
41
+ get?(name: string): unknown
42
+ inject(deps: readonly string[], fn: (ctx: ClientContext) => void): unknown
43
+ effect(fn: () => unknown, label?: string): unknown
44
+ slots?: SlotsService
45
+ locale?: LocaleService
46
+ }
47
+
48
+ /** 插件级 inject 只声明三代都存在的服务。 */
49
+ export const inject = ['slots', 'locale'] as const
50
+
51
+ /** 当前语言的取词函数(注册后由 locale 服务提供;拿不到 bind 时回落 zh 字典)。 */
52
+ let currentT: (key: string) => string = (key) => {
53
+ const zh = (dictionaries as Record<string, Record<string, string>>).zh
54
+ return zh[key] ?? key
55
+ }
56
+
57
+ /** 每个面的独立 try/catch:一面抛错不带走其它面。 */
58
+ function safe(ctx: ClientContext, tag: string, fn: () => void): void {
59
+ try {
60
+ fn()
61
+ } catch (error) {
62
+ // 农场/真机拿不到 console 时也要留痕:失败面写进 window,供探针直接读取。
63
+ const surface = ((globalThis as Record<string, unknown>).__dccSurf ??= []) as string[]
64
+ surface.push(`${tag}: ${String((error as Error)?.message ?? error)}`)
65
+ const logger = typeof ctx.get === 'function' ? ctx.get('logger') as { warn?(msg: string): void } : undefined
66
+ if (typeof logger?.warn === 'function') logger.warn(`[dsh-cookie-cleaner] ${tag} failed: ${String((error as Error)?.message ?? error)}`)
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 浏览器半入口。
72
+ * @param ctx client context。
73
+ */
74
+ export function apply(ctx: ClientContext): void {
75
+ // 字典注册:一次调用带 9 语(map 式注册要求宿主 locale 服务接受任意语言码)。
76
+ safe(ctx, 'locale.register', () => {
77
+ if (typeof ctx.locale?.register !== 'function') throw new Error('locale service unavailable')
78
+ ctx.locale.register(NS, dictionaries)
79
+ const bind = ctx.locale.bind?.(NS)
80
+ if (typeof bind === 'function') {
81
+ // bind 是活的取值器:换语言后重渲染即跟上新值,卡片不自存语言副本。
82
+ currentT = (key: string) => bind(key)
83
+ }
84
+ })
85
+
86
+ // 席位 A:设置页顶级独立节(范式 A,不参与家族 tab 选举)。
87
+ safe(ctx, 'settings.section', () => {
88
+ const slots = ctx.slots
89
+ if (slots?.inject === undefined || slots.register === undefined) throw new Error('slots service unavailable')
90
+ slots.inject('settings.section', function* () {
91
+ yield slots.register({
92
+ name: 'settings.section',
93
+ id: NS,
94
+ order: 45,
95
+ label: () => currentT('section.title'),
96
+ locale: NS,
97
+ inject: () => ({ t: (key: string) => currentT(key) }),
98
+ }, PatchCard)
99
+ })
100
+ })
101
+
102
+ // 席位 B:插件页配置卡(0.2.x 上「导出 Config 自动出表单」不成立,必须显式挂)。
103
+ // 这个槽是 **keyed** 形态,key = bundle 的包名(真机报错:keyed slot requires options.key)。
104
+ safe(ctx, 'plugins.bundle.config', () => {
105
+ const slots = ctx.slots
106
+ if (slots?.inject === undefined || slots.register === undefined) throw new Error('slots service unavailable')
107
+ slots.inject('plugins.bundle.config', function* () {
108
+ yield slots.register({
109
+ name: 'plugins.bundle.config',
110
+ key: NS,
111
+ order: 45,
112
+ label: () => currentT('section.title'),
113
+ locale: NS,
114
+ inject: () => ({ t: (key: string) => currentT(key) }),
115
+ }, PatchCard)
116
+ })
117
+ })
118
+
119
+ // 装载自检:键集没注册全就是构建坏了,立刻留痕而不是等用户点开空卡。
120
+ safe(ctx, 'dictionary sanity', () => {
121
+ const langs = Object.keys(dictionaries)
122
+ if (langs.length !== 9) throw new Error(`expected 9 languages, got ${String(langs.length)}`)
123
+ const missing = langs.filter((lang) => {
124
+ const dict = (dictionaries as Record<string, Record<string, string>>)[lang]
125
+ return UI_KEYS.some((key) => typeof dict[key] !== 'string' || dict[key] === '')
126
+ })
127
+ if (missing.length > 0) throw new Error(`empty keys for ${missing.join(', ')}`)
128
+ })
129
+ }
@@ -1,84 +1,91 @@
1
- /**
2
- * dsh-cookie-cleaner — client 半的界面文案(9 语)。
3
- *
4
- * 为什么在浏览器侧自己渲染文本,而不是显示宿主算好的句子:
5
- * 浏览器语言与宿主进程语言可以不同(宿主跟 LANG 走,UI 跟设置走),
6
- * 面板显示服务端文案会让「中文宿主 + 英文界面」这种常见组合输出半中英。
7
- * 所以宿主只回 `{code, params}`,卡片按 `locale` 服务的当前语言渲染。
8
- *
9
- * P1-P12 判定码复用 `src/locales-patch.js`(宿主半与 CLI 同源),这里只加界面 chrome
10
- * 并把两张表压平成 `locale.register` 需要的 key→string 形态——加规则时不用改两处。
11
- */
12
- import { PATCH_CODES, PATCH_LANGS, PATCH_TEXT } from '../locales-patch.js'
13
-
14
- export type PatchLang = typeof PATCH_LANGS[number]
15
-
16
- /** 字典命名空间 = npm 包名(与卡 id、桥路径同串)。 */
17
- export const NS = 'dsh-cookie-cleaner'
18
-
19
- /** 界面 chrome 文案(9 语并排,顺序同 PATCH_LANGS)。 */
20
- const t = (zh: string, en: string, ja: string, ko: string, fr: string, de: string, it: string, ru: string, es: string) =>
21
- ({ zh, en, ja, ko, fr, de, it, ru, es }) as Record<PatchLang, string>
22
-
23
- const CHROME: Record<string, Record<PatchLang, string>> = {
24
- 'section.title': t('Cookie 清理器', 'Cookie Cleaner', 'Cookie クリーナー', 'Cookie 청소기', 'Nettoyeur de cookies', 'Cookie-Reiniger', 'Pulitore cookie', 'Очистка cookie', 'Limpiador de cookies'),
25
- 'card.title': t('profile patch 体检与修复', 'Profile patch check & fix', 'profile patch の点検と修復', 'profile patch 점검 및 복구', 'Contrôle et réparation du patch de profil', 'Prüfung & Korrektur des Profil-Patches', 'Controllo e correzione del patch del profilo', 'Проверка и исправление патча профиля', 'Revisión y reparación del patch de perfil'),
26
- 'action.check': t('体检', 'Check', '点検', '점검', 'Contrôler', 'Prüfen', 'Controlla', 'Проверить', 'Revisar'),
27
- 'action.fix': t('修复', 'Fix', '修復', '복구', 'Réparer', 'Korrigieren', 'Correggi', 'Исправить', 'Reparar'),
28
- 'action.revert': t('回滚', 'Revert', '戻す', '되돌리기', 'Annuler', 'Rückgängig', 'Ripristina', 'Отменить', 'Revertir'),
29
- // 端口控件已从面板移除(真正有效的是 cookie 寿命注入),所以这里不再有 port.* 文案;
30
- // 端口相关句子统一走 `x.*`(与宿主/CLI 同一张表)。
31
- 'state.busy': t('进行中…', 'working…', '処理中…', '처리 중…', 'en cours…', 'läuft…', 'in corso…', 'выполняется…', 'en curso…'),
32
- 'state.failed': t('动作失败:{message}', 'action failed: {message}', 'アクション失敗:{message}', '동작 실패: {message}', 'échec de l\'action : {message}', 'Aktion fehlgeschlagen: {message}', 'azione fallita: {message}', 'действие не удалось: {message}', 'acción falló: {message}'),
33
- 'state.offline': t('宿主未提供 config-editor(老线或未装配),本面板无法在线体检/修复', 'the host exposes no config-editor (older line or not assembled); this panel cannot check or fix online', '宿主に config-editor が無く(旧ライン/未装配)、本パネルではオンライン点検・修復不可', '호스트에 config-editor가 없음(구 라인/미조립) → 이 패널에서 온라인 점검·복구 불가', 'l\'hôte n\'expose pas de config-editor (ancienne ligne ou non assemblé) ; ce panneau ne peut ni contrôler ni réparer', 'der Host stellt keinen config-editor bereit (ältere Zeile oder nicht montiert); dieses Panel kann nicht online prüfen oder korrigieren', 'l\'host non espone config-editor (linea vecchia o non assemblato); questo pannello non può controllare né correggere online', 'хост не даёт config-editor (старая линия или не собран); эта панель не может проверять или исправлять онлайн', 'el host no expone config-editor (línea antigua o no ensamblado); este panel no puede revisar ni reparar en línea'),
34
- 'row.connection': t('connection(cookie 寿命)', 'connection (cookie lifetime)', 'connection(cookie 寿命)', 'connection(cookie 수명)', 'connection (durée de vie des cookies)', 'connection (Cookie-Lebensdauer)', 'connection (durata cookie)', 'connection (срок жизни cookie)', 'connection (duración de cookies)'),
35
- 'row.webserver': t('webserver(启动面)', 'webserver (launch surface)', 'webserver(起動面)', 'webserver(시작 면)', 'webserver (surface de lancement)', 'webserver (Startebene)', 'webserver (livello di avvio)', 'webserver (слой запуска)', 'webserver (capa de arranque)'),
36
- 'level.ok': t('结构健康', 'structurally sound', '構造は健全', '구조 정상', 'structure saine', 'strukturell in Ordnung', 'struttura integra', 'структура здорова', 'estructura sana'),
37
- 'level.warn': t('有偏差', 'deviates', '偏差あり', '편차 있음', 'dérive', 'Abweichung', 'in deviazione', 'отклонение', 'desviación'),
38
- 'level.fail': t('会失效', 'will not take effect', '効きません', '적용 안 됨', 'sans effet', 'wirkt nicht', 'non avrà effetto', 'не сработает', 'no surtirá efecto'),
39
- 'level.skipped': t('无法判定', 'cannot decide', '判定不能', '판단 불가', 'indécidable', 'nicht bestimmbar', 'indecidibile', 'нельзя определить', 'indecidible'),
40
- 'note.webserver': t('webserver 行只体检不自动写(端口钉死属启动行为面)', 'the webserver row is checked but never auto-written (pinning the port is a launch-behaviour decision)', 'webserver 行は体検のみ・自動書き込みなし(ポート固定は起動挙動の話)', 'webserver 행은 점검만, 자동 기록 없음(포트 고정은 시작 동작 판단)', 'la ligne webserver est contrôlée mais jamais écrite (figer le port relève du lancement)', 'die webserver-Zeile wird nur geprüft, nie geschrieben (Portfestlegung ist Startverhalten)', 'la riga webserver è solo controllata, mai scritta (fissare la porta riguarda l\'avvio)', 'строка webserver только проверяется, не пишется (фиксация порта — вопрос запуска)', 'la fila webserver solo se revisa, nunca se escribe (fijar el puerto concierne al arranque)'),
41
- 'fix.done': t('已写入:{changed}', 'written: {changed}', '書き込み完了:{changed}', '기록됨: {changed}', 'écrit : {changed}', 'geschrieben: {changed}', 'scritto: {changed}', 'записано: {changed}', 'escrito: {changed}'),
42
- 'fix.noop': t('无需写入(已在目标档)', 'nothing to write (already on target)', '書き込み不要(目標達成済み)', '기록 불필요(이미 목표)', 'rien à écrire (déjà à la cible)', 'nichts zu schreiben (bereits am Ziel)', 'nulla da scrivere (già all\'obiettivo)', 'нечего писать (уже в цели)', 'nada que escribir (ya en el objetivo)'),
43
- 'fix.blocked': t('判定为不可动作({codes}):需按提示手工修文件', 'judged not actionable ({codes}): fix the file by hand as suggested', '動作不可と判定({codes}):表示どおり手動でファイルを修正', '조치 불가({codes}): 안내대로 파일을 직접 수정', 'jugé non exécutable ({codes}) : corrigez le fichier à la main', 'als nicht ausführbar eingestuft ({codes}): Datei wie vorgeschlagen von Hand korrigieren', 'giudicato non eseguibile ({codes}): correggere a mano il file come suggerito', 'признано невыполнимым ({codes}): правьте файл вручную по подсказке', 'juzgado no accionable ({codes}): corrige el archivo a mano como se sugiere'),
44
- 'revert.done': t('已回滚:{changed}', 'rolled back: {changed}', 'ロールバック済み:{changed}', '되돌림: {changed}', 'annulé : {changed}', 'zurückgerollt: {changed}', 'ripristinato: {changed}', 'откатлено: {changed}', 'revertido: {changed}'),
45
- 'revert.none': t('没有可回滚的快照(修复一次才会留一份)', 'no snapshot to roll back (a successful fix keeps one)', '回滚用スナップショット無し(修復成功時に 1 件保存)', '롤백 스냅샷 없음(복구 성공 시 1개 보관)', 'aucun instantané à restaurer (une réparation réussie en garde un)', 'kein Snapshot zum Zurückrollen (ein erfolgreicher Fix hinterlässt einen)', 'nessuno snapshot da ripristinare (una correzione riuscita ne conserva uno)', 'нет снимка для отката (успешное исправление сохраняет один)', 'no hay instantánea a la que volver (una reparación correcta guarda una)'),
46
- 'lastCheck': t('最近体检:{at}', 'last check: {at}', '最近の点検:{at}', '마지막 점검: {at}', 'dernier contrôle : {at}', 'letzte Prüfung: {at}', 'ultimo controllo: {at}', 'последняя проверка: {at}', 'última revisión: {at}'),
47
- 'guard.title': t('运行期守护(Set-Cookie 退休旧 cookie)', 'Runtime guard (retire stale cookies via Set-Cookie)', 'ランタイム守護(Set-Cookie で古い cookie を引退)', '런타임 가드 (Set-Cookie 로 오래된 cookie 정리)', 'Garde en direct (retirer les vieux cookies via Set-Cookie)', 'Laufzeit-Wächter (alte Cookies via Set-Cookie entfernen)', 'Guardia runtime (ritira i cookie vecchi via Set-Cookie)', 'Страж (удаление старых cookie через Set-Cookie)', 'Guardia en ejecución (retirar cookies viejas vía Set-Cookie)'),
48
- 'guard.enable': t('启用运行期守护', 'Enable runtime guard', 'ランタイム守護を有効化', '런타임 가드 켜기', 'Activer la garde en direct', 'Laufzeit-Wächter aktivieren', 'Abilita la guardia runtime', 'Включить стража', 'Activar guardia en ejecución'),
49
- 'guard.retireAbove': t('触发阈值(条数 > 此值才退休,0=不设阈值)', 'Trigger threshold (retire only when count > this; 0 = no threshold)', '発動しきい値(件数 > この値で引退、0=なし)', '발동 임계값(개수 > 이 값이면 정리, 0=없음)', 'Seuil de déclenchement (retirer si nombre > cette valeur ; 0 = aucun)', 'Auslöseschwelle (erst wenn Anzahl > dieser Wert; 0 = keine)', 'Soglia di attivazione (ritira se conteggio > valore; 0 = nessuna)', 'Порог срабатывания (удалять если число > значения; 0 = нет)', 'Umbral de disparo (retirar si cantidad > valor; 0 = ninguno)'),
50
- 'guard.keep': t('保留尾部条数(keep)', 'Keep tail count (keep)', '末尾保持件数(keep)', '꼬리 유지 개수(keep)', 'Nombre conservé en queue (keep)', 'Anzahl am Ende behalten (keep)', 'Numero mantenuto in coda (keep)', 'Держать в хвосте (keep)', 'Cantidad retenida en cola (keep)'),
51
- 'guard.saved': t('已写入守护设置(HMR 热生效)', 'guard settings written (applies via HMR)', '守護設定を書き込みました(HMR で反映)', '가드 설정 기록됨(HMR 적용)', 'réglages de la garde écrits (appliqués par HMR)', 'Wächter-Einstellungen geschrieben (via HMR)', 'impostazioni della guardia scritte (via HMR)', 'настройки стража записаны (через HMR)', 'ajustes de la guardia escritos (vía HMR)'),
52
- 'guard.noop': t('无变化,未写入', 'no change, nothing written', '変更なし、書き込みなし', '변경 없음, 기록 안 함', 'aucun changement', 'keine Änderung', 'nessun cambiamento', 'без изменений', 'sin cambios'),
53
- 'guard.unavailable': t('当前宿主拿不到本插件配置行(无 config-editor),无法在面板改守护设置', 'the host exposes no editable row for this plugin; cannot change guard settings here', 'このホストでは本プラグインの設定行を取得できず、パネルでは変更不可', '이 호스트에서 플러그인 설정 행을 얻을 수 없어 패널에서 변경 불가', 'cet hôte n\'expose pas de ligne éditable pour ce plugin', 'dieser Host hat keine editierbare Zeile für dieses Plugin', 'questo host non espone una riga modificabile per il plugin', 'этот хост не даёт редактируемую строку плагина', 'este host no expone una fila editable para este plugin'),
54
- }
55
-
56
- /** 把共享判定表压平成 `p.P5` 形态的键(宿主只回 code,语言由界面决定)。 */
57
- function flatten(bucket: Record<string, Record<PatchLang, string>>, prefix: string) {
58
- const out: Record<string, Record<PatchLang, string>> = {}
59
- for (const [code, entry] of Object.entries(bucket)) out[`${prefix}${code}`] = entry
60
- return out
61
- }
62
-
63
- const MERGED: Record<string, Record<PatchLang, string>> = {
64
- ...CHROME,
65
- ...flatten(PATCH_CODES, 'p.'),
66
- ...flatten(PATCH_TEXT, 'x.'),
67
- }
68
-
69
- /** 界面用到的全部键(测试用它核对 9 语逐键相等)。 */
70
- export const UI_KEYS: readonly string[] = Object.keys(MERGED)
71
-
72
- /** `locale.register(NS, dictionaries)` 的入参。 */
73
- export const dictionaries = Object.fromEntries(
74
- PATCH_LANGS.map((lang) => [lang, Object.fromEntries(UI_KEYS.map((key) => [key, MERGED[key][lang]]))]),
75
- ) as Record<PatchLang, Record<string, string>>
76
-
77
- /** 本地插值(`{name}` 形态,与宿主字典同规则;缺参原样留形便于发现漏参)。 */
78
- export function render(text: string, params: Record<string, unknown> = {}): string {
79
- return text.replace(/\{(\w+)\}/g, (_m, name: string) => {
80
- const value = params[name]
81
- if (value === undefined) return `{${name}}`
82
- return Array.isArray(value) ? value.join(', ') : String(value)
83
- })
84
- }
1
+ /**
2
+ * dsh-cookie-cleaner — client 半的界面文案(9 语)。
3
+ *
4
+ * 为什么在浏览器侧自己渲染文本,而不是显示宿主算好的句子:
5
+ * 浏览器语言与宿主进程语言可以不同(宿主跟 LANG 走,UI 跟设置走),
6
+ * 面板显示服务端文案会让「中文宿主 + 英文界面」这种常见组合输出半中英。
7
+ * 所以宿主只回 `{code, params}`,卡片按 `locale` 服务的当前语言渲染。
8
+ *
9
+ * P1-P12 判定码复用 `src/locales-patch.js`(宿主半与 CLI 同源),这里只加界面 chrome
10
+ * 并把两张表压平成 `locale.register` 需要的 key→string 形态——加规则时不用改两处。
11
+ */
12
+ import { PATCH_CODES, PATCH_LANGS, PATCH_TEXT } from '../locales-patch.js'
13
+
14
+ export type PatchLang = typeof PATCH_LANGS[number]
15
+
16
+ /** 字典命名空间 = npm 包名(与卡 id、桥路径同串)。 */
17
+ export const NS = 'dsh-cookie-cleaner'
18
+
19
+ /** 界面 chrome 文案(9 语并排,顺序同 PATCH_LANGS)。 */
20
+ const t = (zh: string, en: string, ja: string, ko: string, fr: string, de: string, it: string, ru: string, es: string) =>
21
+ ({ zh, en, ja, ko, fr, de, it, ru, es }) as Record<PatchLang, string>
22
+
23
+ const CHROME: Record<string, Record<PatchLang, string>> = {
24
+ 'section.title': t('Cookie 清理器', 'Cookie Cleaner', 'Cookie クリーナー', 'Cookie 청소기', 'Nettoyeur de cookies', 'Cookie-Reiniger', 'Pulitore cookie', 'Очистка cookie', 'Limpiador de cookies'),
25
+ 'card.title': t('profile patch 体检与修复', 'Profile patch check & fix', 'profile patch の点検と修復', 'profile patch 점검 및 복구', 'Contrôle et réparation du patch de profil', 'Prüfung & Korrektur des Profil-Patches', 'Controllo e correzione del patch del profilo', 'Проверка и исправление патча профиля', 'Revisión y reparación del patch de perfil'),
26
+ 'action.check': t('体检', 'Check', '点検', '점검', 'Contrôler', 'Prüfen', 'Controlla', 'Проверить', 'Revisar'),
27
+ 'action.fix': t('修复', 'Fix', '修復', '복구', 'Réparer', 'Korrigieren', 'Correggi', 'Исправить', 'Reparar'),
28
+ 'action.revert': t('回滚', 'Revert', '戻す', '되돌리기', 'Annuler', 'Rückgängig', 'Ripristina', 'Отменить', 'Revertir'),
29
+ // 端口控件已从面板移除(真正有效的是 cookie 寿命注入),所以这里不再有 port.* 文案;
30
+ // 端口相关句子统一走 `x.*`(与宿主/CLI 同一张表)。
31
+ 'state.busy': t('进行中…', 'working…', '処理中…', '처리 중…', 'en cours…', 'läuft…', 'in corso…', 'выполняется…', 'en curso…'),
32
+ 'state.failed': t('动作失败:{message}', 'action failed: {message}', 'アクション失敗:{message}', '동작 실패: {message}', 'échec de l\'action : {message}', 'Aktion fehlgeschlagen: {message}', 'azione fallita: {message}', 'действие не удалось: {message}', 'acción falló: {message}'),
33
+ 'state.offline': t('宿主未提供 config-editor(老线或未装配),本面板无法在线体检/修复', 'the host exposes no config-editor (older line or not assembled); this panel cannot check or fix online', '宿主に config-editor が無く(旧ライン/未装配)、本パネルではオンライン点検・修復不可', '호스트에 config-editor가 없음(구 라인/미조립) → 이 패널에서 온라인 점검·복구 불가', 'l\'hôte n\'expose pas de config-editor (ancienne ligne ou non assemblé) ; ce panneau ne peut ni contrôler ni réparer', 'der Host stellt keinen config-editor bereit (ältere Zeile oder nicht montiert); dieses Panel kann nicht online prüfen oder korrigieren', 'l\'host non espone config-editor (linea vecchia o non assemblato); questo pannello non può controllare né correggere online', 'хост не даёт config-editor (старая линия или не собран); эта панель не может проверять или исправлять онлайн', 'el host no expone config-editor (línea antigua o no ensamblado); este panel no puede revisar ni reparar en línea'),
34
+ 'row.connection': t('connection(cookie 寿命)', 'connection (cookie lifetime)', 'connection(cookie 寿命)', 'connection(cookie 수명)', 'connection (durée de vie des cookies)', 'connection (Cookie-Lebensdauer)', 'connection (durata cookie)', 'connection (срок жизни cookie)', 'connection (duración de cookies)'),
35
+ 'row.webserver': t('webserver(启动面)', 'webserver (launch surface)', 'webserver(起動面)', 'webserver(시작 면)', 'webserver (surface de lancement)', 'webserver (Startebene)', 'webserver (livello di avvio)', 'webserver (слой запуска)', 'webserver (capa de arranque)'),
36
+ 'level.ok': t('结构健康', 'structurally sound', '構造は健全', '구조 정상', 'structure saine', 'strukturell in Ordnung', 'struttura integra', 'структура здорова', 'estructura sana'),
37
+ 'level.warn': t('有偏差', 'deviates', '偏差あり', '편차 있음', 'dérive', 'Abweichung', 'in deviazione', 'отклонение', 'desviación'),
38
+ 'level.fail': t('会失效', 'will not take effect', '効きません', '적용 안 됨', 'sans effet', 'wirkt nicht', 'non avrà effetto', 'не сработает', 'no surtirá efecto'),
39
+ 'level.skipped': t('无法判定', 'cannot decide', '判定不能', '판단 불가', 'indécidable', 'nicht bestimmbar', 'indecidibile', 'нельзя определить', 'indecidible'),
40
+ 'note.webserver': t('webserver 行只体检不自动写(端口钉死属启动行为面)', 'the webserver row is checked but never auto-written (pinning the port is a launch-behaviour decision)', 'webserver 行は体検のみ・自動書き込みなし(ポート固定は起動挙動の話)', 'webserver 행은 점검만, 자동 기록 없음(포트 고정은 시작 동작 판단)', 'la ligne webserver est contrôlée mais jamais écrite (figer le port relève du lancement)', 'die webserver-Zeile wird nur geprüft, nie geschrieben (Portfestlegung ist Startverhalten)', 'la riga webserver è solo controllata, mai scritta (fissare la porta riguarda l\'avvio)', 'строка webserver только проверяется, не пишется (фиксация порта — вопрос запуска)', 'la fila webserver solo se revisa, nunca se escribe (fijar el puerto concierne al arranque)'),
41
+ 'fix.done': t('已写入:{changed}', 'written: {changed}', '書き込み完了:{changed}', '기록됨: {changed}', 'écrit : {changed}', 'geschrieben: {changed}', 'scritto: {changed}', 'записано: {changed}', 'escrito: {changed}'),
42
+ 'fix.noop': t('无需写入(已在目标档)', 'nothing to write (already on target)', '書き込み不要(目標達成済み)', '기록 불필요(이미 목표)', 'rien à écrire (déjà à la cible)', 'nichts zu schreiben (bereits am Ziel)', 'nulla da scrivere (già all\'obiettivo)', 'нечего писать (уже в цели)', 'nada que escribir (ya en el objetivo)'),
43
+ 'fix.blocked': t('判定为不可动作({codes}):需按提示手工修文件', 'judged not actionable ({codes}): fix the file by hand as suggested', '動作不可と判定({codes}):表示どおり手動でファイルを修正', '조치 불가({codes}): 안내대로 파일을 직접 수정', 'jugé non exécutable ({codes}) : corrigez le fichier à la main', 'als nicht ausführbar eingestuft ({codes}): Datei wie vorgeschlagen von Hand korrigieren', 'giudicato non eseguibile ({codes}): correggere a mano il file come suggerito', 'признано невыполнимым ({codes}): правьте файл вручную по подсказке', 'juzgado no accionable ({codes}): corrige el archivo a mano como se sugiere'),
44
+ 'revert.done': t('已回滚:{changed}', 'rolled back: {changed}', 'ロールバック済み:{changed}', '되돌림: {changed}', 'annulé : {changed}', 'zurückgerollt: {changed}', 'ripristinato: {changed}', 'откатлено: {changed}', 'revertido: {changed}'),
45
+ 'revert.none': t('没有可回滚的快照(修复一次才会留一份)', 'no snapshot to roll back (a successful fix keeps one)', '回滚用スナップショット無し(修復成功時に 1 件保存)', '롤백 스냅샷 없음(복구 성공 시 1개 보관)', 'aucun instantané à restaurer (une réparation réussie en garde un)', 'kein Snapshot zum Zurückrollen (ein erfolgreicher Fix hinterlässt einen)', 'nessuno snapshot da ripristinare (una correzione riuscita ne conserva uno)', 'нет снимка для отката (успешное исправление сохраняет один)', 'no hay instantánea a la que volver (una reparación correcta guarda una)'),
46
+ 'lastCheck': t('最近体检:{at}', 'last check: {at}', '最近の点検:{at}', '마지막 점검: {at}', 'dernier contrôle : {at}', 'letzte Prüfung: {at}', 'ultimo controllo: {at}', 'последняя проверка: {at}', 'última revisión: {at}'),
47
+ 'guard.title': t('运行期守护(Set-Cookie 退休旧 cookie)', 'Runtime guard (retire stale cookies via Set-Cookie)', 'ランタイム守護(Set-Cookie で古い cookie を引退)', '런타임 가드 (Set-Cookie 로 오래된 cookie 정리)', 'Garde en direct (retirer les vieux cookies via Set-Cookie)', 'Laufzeit-Wächter (alte Cookies via Set-Cookie entfernen)', 'Guardia runtime (ritira i cookie vecchi via Set-Cookie)', 'Страж (удаление старых cookie через Set-Cookie)', 'Guardia en ejecución (retirar cookies viejas vía Set-Cookie)'),
48
+ 'guard.retireAbove': t('触发阈值(条数 > 此值才退休,0=不设阈值)', 'Trigger threshold (retire only when count > this; 0 = no threshold)', '発動しきい値(件数 > この値で引退、0=なし)', '발동 임계값(개수 > 이 값이면 정리, 0=없음)', 'Seuil de déclenchement (retirer si nombre > cette valeur ; 0 = aucun)', 'Auslöseschwelle (erst wenn Anzahl > dieser Wert; 0 = keine)', 'Soglia di attivazione (ritira se conteggio > valore; 0 = nessuna)', 'Порог срабатывания (удалять если число > значения; 0 = нет)', 'Umbral de disparo (retirar si cantidad > valor; 0 = ninguno)'),
49
+ 'guard.keep': t('保留尾部条数(keep)', 'Keep tail count (keep)', '末尾保持件数(keep)', '꼬리 유지 개수(keep)', 'Nombre conservé en queue (keep)', 'Anzahl am Ende behalten (keep)', 'Numero mantenuto in coda (keep)', 'Держать в хвосте (keep)', 'Cantidad retenida en cola (keep)'),
50
+ 'guard.saved': t('已写入守护设置(HMR 热生效)', 'guard settings written (applies via HMR)', '守護設定を書き込みました(HMR で反映)', '가드 설정 기록됨(HMR 적용)', 'réglages de la garde écrits (appliqués par HMR)', 'Wächter-Einstellungen geschrieben (via HMR)', 'impostazioni della guardia scritte (via HMR)', 'настройки стража записаны (через HMR)', 'ajustes de la guardia escritos (vía HMR)'),
51
+ 'guard.noop': t('无变化,未写入', 'no change, nothing written', '変更なし、書き込みなし', '변경 없음, 기록 안 함', 'aucun changement', 'keine Änderung', 'nessun cambiamento', 'без изменений', 'sin cambios'),
52
+ 'guard.enableRetire': t('退休陈旧 cookie(推荐开启)', 'Retire stale cookies (recommended)', '古い cookie を引退(推奨)', '오래된 cookie 정리 (권장)', 'Retirer les vieux cookies (recommandé)', 'Alte Cookies entfernen (empfohlen)', 'Ritira i cookie vecchi (consigliato)', 'Удалять старые cookie (рекомендуется)', 'Retirar cookies viejos (recomendado)'),
53
+ 'legacy.title': t('历史注入残留', 'Legacy injection residue', '過去の注入残り', '과거 주입 잔여물', 'Résidu d\'injection historique', 'Alt-Injektionsrest', 'Residuo di iniezione storica', 'Остаток старой инъекции', 'Residuo de inyección histórica'),
54
+ 'legacy.found': t('旧版「应用端口」写进 profile 的表达式:{expr}', 'written into the profile by the old "apply port" action: {expr}', '旧版「ポート適用」が profile に書いた式:{expr}', '구버전 "포트 적용"이 profile 에 쓴 식: {expr}', 'écrit dans le profil par l\'ancienne action « appliquer le port » : {expr}', 'vom alten "Port anwenden" ins Profil geschrieben: {expr}', 'scritto nel profilo dalla vecchia azione "applica porta": {expr}', 'записано в profile старым действием «применить порт»: {expr}', 'escrito en el perfil por la antigua acción "aplicar puerto": {expr}'),
55
+ 'legacy.clean': t('清理这一行', 'Clean this row', 'この行を整理', '이 행 정리', 'Nettoyer cette ligne', 'Diese Zeile bereinigen', 'Pulisci questa riga', 'Очистить эту строку', 'Limpiar esta fila'),
56
+ 'legacy.cleaned': t('已清理:该键回落到宿主默认', 'cleaned: the key falls back to the host default', '整理しました:ホスト既定に戻ります', '정리됨: 호스트 기본값으로 복귀', 'nettoyé : la clé revient à la valeur par défaut', 'bereinigt: der Schlüssel fällt auf den Host-Standard zurück', 'pulito: la chiave torna al valore predefinito', 'очищено: ключ возвращается к значению хоста', 'limpiado: la clave vuelve al valor del host'),
57
+ 'legacy.noop': t('没有可清理的内容', 'nothing to clean', '整理するものはありません', '정리할 항목 없음', 'rien à nettoyer', 'nichts zu bereinigen', 'niente da pulire', 'нечего очищать', 'nada que limpiar'),
58
+ 'legacy.unsupported': t('当前宿主(<0.2.2-rc.2)仍需要钉端口这条缓解,只报告不清理', 'this host (<0.2.2-rc.2) still relies on the pinned port; reporting only', 'このホスト(<0.2.2-rc.2)はポート固定が必要なため報告のみ', '이 호스트(<0.2.2-rc.2)는 포트 고정이 필요해 보고만 합니다', 'cet hôte (<0.2.2-rc.2) dépend encore du port fixé ; rapport seulement', 'dieser Host (<0.2.2-rc.2) braucht den festen Port noch; nur Bericht', 'questo host (<0.2.2-rc.2) richiede ancora la porta fissata; solo segnalazione', 'этот хост (<0.2.2-rc.2) ещё полагается на фиксированный порт; только отчёт', 'este host (<0.2.2-rc.2) aún depende del puerto fijo; solo informe'),
59
+ 'guard.enableBudget': t('抬高请求头预算(默认关,放宽 431 触发线)', 'Raise the header budget (off by default; loosens the 431 threshold)', 'ヘッダー予算を引き上げ(既定オフ。431 の閾値を緩める)', '헤더 예산 올리기 (기본 꺼짐, 431 임계값 완화)', 'Relever le budget d\'en-têtes (désactivé par défaut ; assouplit le seuil 431)', 'Header-Budget anheben (standardmäßig aus; lockert die 431-Schwelle)', 'Alza il budget header (disattivato; allenta la soglia 431)', 'Поднять лимит заголовков (по умолчанию выкл.; ослабляет порог 431)', 'Elevar el presupuesto de cabeceras (desactivado; relaja el umbral 431)'),
60
+ 'guard.unavailable': t('当前宿主拿不到本插件配置行(无 config-editor),无法在面板改守护设置', 'the host exposes no editable row for this plugin; cannot change guard settings here', 'このホストでは本プラグインの設定行を取得できず、パネルでは変更不可', '이 호스트에서 플러그인 설정 행을 얻을 수 없어 패널에서 변경 불가', 'cet hôte n\'expose pas de ligne éditable pour ce plugin', 'dieser Host hat keine editierbare Zeile für dieses Plugin', 'questo host non espone una riga modificabile per il plugin', 'этот хост не даёт редактируемую строку плагина', 'este host no expone una fila editable para este plugin'),
61
+ }
62
+
63
+ /** 把共享判定表压平成 `p.P5` 形态的键(宿主只回 code,语言由界面决定)。 */
64
+ function flatten(bucket: Record<string, Record<PatchLang, string>>, prefix: string) {
65
+ const out: Record<string, Record<PatchLang, string>> = {}
66
+ for (const [code, entry] of Object.entries(bucket)) out[`${prefix}${code}`] = entry
67
+ return out
68
+ }
69
+
70
+ const MERGED: Record<string, Record<PatchLang, string>> = {
71
+ ...CHROME,
72
+ ...flatten(PATCH_CODES, 'p.'),
73
+ ...flatten(PATCH_TEXT, 'x.'),
74
+ }
75
+
76
+ /** 界面用到的全部键(测试用它核对 9 语逐键相等)。 */
77
+ export const UI_KEYS: readonly string[] = Object.keys(MERGED)
78
+
79
+ /** `locale.register(NS, dictionaries)` 的入参。 */
80
+ export const dictionaries = Object.fromEntries(
81
+ PATCH_LANGS.map((lang) => [lang, Object.fromEntries(UI_KEYS.map((key) => [key, MERGED[key][lang]]))]),
82
+ ) as Record<PatchLang, Record<string, string>>
83
+
84
+ /** 本地插值(`{name}` 形态,与宿主字典同规则;缺参原样留形便于发现漏参)。 */
85
+ export function render(text: string, params: Record<string, unknown> = {}): string {
86
+ return text.replace(/\{(\w+)\}/g, (_m, name: string) => {
87
+ const value = params[name]
88
+ if (value === undefined) return `{${name}}`
89
+ return Array.isArray(value) ? value.join(', ') : String(value)
90
+ })
91
+ }