@verbaly/compiler 0.68.0 → 0.69.0

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/README.md CHANGED
@@ -28,6 +28,7 @@ npx verbaly extract # sync catalogs + types
28
28
  npx verbaly extract --watch # keep extracting as you code (dev loop)
29
29
  npx verbaly extract --prune # drop orphaned keys (waits while any source file does not parse)
30
30
  npx verbaly extract --dry-run # say what extract would add and prune, write nothing
31
+ npx verbaly typegen # write the TypeScript types alone (CI: run it before tsc)
31
32
  npx verbaly status # coverage per locale, plus unreviewed, broken and outdated counts
32
33
  npx verbaly check # exit 1 if anything is missing or broken (CI)
33
34
  npx verbaly translate # fill missing translations via Claude (or your provider), as drafts
@@ -39,7 +40,7 @@ npx verbaly pseudo # generate a pseudo-locale catalog for i18n QA (en-XA
39
40
  npx verbaly render # pre-fill data-verbaly HTML per locale (SSG, kills the FOUC)
40
41
  ```
41
42
 
42
- Reads `verbaly.config.{js,mjs,ts,mts,json}` (TS configs need `esbuild` installed). Generates `locales/<locale>.json` (portable JSON, flat or nested, whichever the file already is) and `verbaly.d.ts` with params typed per key.
43
+ Reads `verbaly.config.{js,mjs,ts,mts,json}` (TS configs need `esbuild` installed). Generates `locales/<locale>.json` (portable JSON, flat or nested, whichever the file already is) and the TypeScript types of your messages, [where your framework looks for them](#-typed-keys-and-where-the-types-live).
43
44
 
44
45
  ## 🚦 The build gate
45
46
 
@@ -104,12 +105,39 @@ t(titles[slug]);
104
105
 
105
106
  **A translation knows which source text it was written for.** For readable keys, the second and third rows, Verbaly keeps a short fingerprint of the source text and of the translation in `.verbaly-state.json`, next to your catalogs. It is taken the moment the translation is written, by `translate`, `import`, Studio or an agent, so a source that changes right after is still caught; `import` takes it from the source text the translator's file carries, so a file made for an older text reads as outdated at once. When the source text changes and the translation does not, the translation is **outdated**: `status`, `check` and `doctor` say so, `review` lists it with both texts, and `review --approve` keeps it if it still holds. Editing the translation clears it on its own. Hash keys never need this, because a new text is a new key.
106
107
 
107
- Three details that catch people out:
108
+ Four details that catch people out:
108
109
 
110
+ - **Keep the files that write `t` inside `include`.** The default reads `src/` and `app/`. A file outside them, like `components/` in a Next app without `src/`, is never extracted, so its text shows in the source language in every language. `@verbaly/next`, the Vite plugin and unplugin say so once when they start, with the pattern to add, and `doctor` lists every such file.
109
111
  - **Name it `t`.** The compiler reads calls named `t`. `const tr = useT()` works at runtime, but `` tr`…` `` is never extracted, so that text stays in the source language. `extract`, `doctor` and the dev servers name every such call with its file and line, in `.vue`, `.svelte` and `.astro` files too, and `--prune` keeps the translations it reads until it is renamed. Only a `useT` or `getT` from a Verbaly package (or auto-imported, as Nuxt does) counts, so a `t` from another library is left alone.
110
112
  - **A number param is formatted for the language.** `{year}` with `2026` renders `2,026` in English, the same as ICU. Pass `String(year)` when the value is a label, not a quantity.
111
113
  - **Literal braces are doubled in a catalog.** `{{` shows `{`. `extract` does it for you from code; a catalog written by hand has to do it itself.
112
114
 
115
+ ## 🔑 Typed keys, and where the types live
116
+
117
+ Every `t` your project holds checks its keys and their params: the one from `virtual:verbaly`, `useT()` in React, Vue and Svelte, `getT()` in Next, and the `t` of an instance from `createInstance` or `createRequestInstance`. A key no catalog has does not compile, a message with a `{name}` asks for it, and Next's `getRequestLocale()` returns one of your locales instead of any string:
118
+
119
+ ```ts
120
+ const t = useT();
121
+ t('settings.save'); // ✓
122
+ t('settings.sav'); // ✗ '"settings.sav"' is not assignable to parameter of type 'TemplateStringsArray | VerbalyKey'
123
+ t('greeting'); // ✗ greeting is "Hello {name}", so it asks for { name }
124
+ ```
125
+
126
+ A key that comes from data is not a literal: declare it with `defineKeys` (above), or say it is one of yours with `key as VerbalyKey`, imported from `virtual:verbaly`.
127
+
128
+ The types are one generated file, written where your framework's TypeScript already reads, so there is nothing to add to `tsconfig.json`:
129
+
130
+ | Project | The file |
131
+ | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
132
+ | Next.js | `.verbaly/types.d.ts`, next to the generated modules. TypeScript skips a dot folder, so its line in `tsconfig.json` is added for you, the way Next adds `.next/types` |
133
+ | Astro | `.astro/integrations/_verbaly_astro/verbaly.d.ts`, the slot Astro gives integrations |
134
+ | Nuxt | `.nuxt/verbaly.d.ts`, the slot Nuxt gives modules |
135
+ | Vite, SvelteKit, webpack, Rollup, esbuild, Rspack, or the CLI alone | `src/verbaly.d.ts`, the folder every app template includes, or `verbaly.d.ts` when there is no `src/` |
136
+
137
+ `extract`, `typegen`, the dev servers, Studio and the MCP server all write that same file, and `dts` in your config still names another one (`dts: false` writes none). A `verbaly.d.ts` an older Verbaly left at the root is removed the first time the new one is written, because the two would declare the same module; one you wrote yourself, without the generated header, is left alone.
138
+
139
+ In CI, write the types before you check them, since a fresh clone has none: `npx verbaly typegen && tsc --noEmit`. In Next, `next typegen` writes them as well, because it loads the same config: `next typegen && tsc --noEmit`.
140
+
113
141
  ## 🤖 Machine translation
114
142
 
115
143
  `verbaly translate` fills the `""` holes `check` reports. The default provider uses Claude via the official SDK; install it as a dev dependency (translation is a build-time step, not an app runtime dependency): `pnpm add -D @anthropic-ai/sdk` (or `npm i -D`), plus `ANTHROPIC_API_KEY`. Default model is `claude-sonnet-5-5` (balanced quality/cost); override with `translate.model` in config or `--model <id>`. Each model is asked for the least thinking it accepts, so any current Claude model works there, and on the models that support it a batch the model declines is answered by Anthropic's recommended fallback model instead of coming back untranslated. Placeholders, variants and tags are validated after translation: anything not preserved verbatim stays `""` so `check` keeps failing.
@@ -303,7 +331,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
303
331
  | Config & catalogs | `loadConfig` `resolveConfig` `targetLocales` `loadCatalogs` `readCatalog` `parseCatalog` `writeCatalog` `clientCatalogs` `needsIcu` `needsRelative` · types `Catalog` `Catalogs` |
304
332
  | Extraction | `syncProject` `extractProject` `collectOrigins` `syncCatalogs` `shippedCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` `watchTree` · types `SyncProjectResult` `SyncResult` `TreeOptions` |
305
333
  | Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · types `DtsOptions` `RuntimeModuleOptions` |
306
- | Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
334
+ | Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `reportOutsideInclude` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
307
335
  | The gate | `check` `validateMessage` `validatePair` `formatCheckResult` `formatCheckWarnings` `collisionEntries` `formatCollision` `formatFinding` `createDevReporter` · types `Finding` `DevReporter` `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `ExtraEntry` `CollisionEntry` `DivergentEntry` `OutdatedEntry` `SourceSite` `StructureIssue` `IssueSeverity` |
308
336
  | Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
309
337
  | Review state | `loadDrafts` `saveDrafts` `markDrafts` `clearDrafts` `effectiveDrafts` `loadState` `readState` `updateState` `recordTranslations` `outdatedTranslations` `STATE_FILE` · types `Drafts` `State` `Fingerprints` `TranslationWrite` |
@@ -335,6 +363,8 @@ const { messages, result } = transformSource(code, id, registry);
335
363
  runBuildGate(cfg, registry);
336
364
  ```
337
365
 
366
+ Call `reportOutsideInclude(cfg)` once when your build starts: it names every file outside `include` that writes a `` t`…` ``, which no build translates. It reads the project itself, so a cached transform never hides one. `writeDts(cfg, catalog)` writes the types where the config resolves them and returns the file and whether it changed.
367
+
338
368
  A dev server that writes the catalogs goes through `syncProject`, the same path `extract`, the MCP server and Studio take: it scans (or takes the registry you hold), syncs, writes the catalogs and the types, and keeps `.verbaly-state.json` in step, in that order. Pass `confirm: true` when your registry is built file by file, so a file that changed on disk unseen is read again before its text is written back. `createDevReporter` then says each of its findings once, says it again if it goes away and comes back, and keeps a long list to a few lines.
339
369
 
340
370
  ## License
@@ -1,4 +1,4 @@
1
- import { i as isModuleNotFound, t as counted } from "./text-SqXoYAIB.js";
1
+ import { n as counted, o as isModuleNotFound } from "./text-Bh96y7ik.js";
2
2
  //#region src/providers/claude.ts
3
3
  const DEFAULT_MODEL = "claude-sonnet-5-5";
4
4
  const FALLBACK_MODELS = /* @__PURE__ */ new Set([
@@ -91,4 +91,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
91
91
  //#endregion
92
92
  export { claudeProvider };
93
93
 
94
- //# sourceMappingURL=claude-BFIWiu_4.js.map
94
+ //# sourceMappingURL=claude-mvcniUPN.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claude-BFIWiu_4.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport { counted } from '../text';\nimport type { TranslateProvider, TranslateRequest } from '../translate';\n\nexport interface ClaudeProviderOptions {\n model?: string;\n apiKey?: string;\n maxTokens?: number;\n}\n\n// balanced default for translation: the current Sonnet, at the price of the one before it\nconst DEFAULT_MODEL = 'claude-sonnet-5-5';\n\n// the models that take fallbacks \"default\": a batch one declines is answered by another model\nconst FALLBACK_MODELS = new Set([\n 'claude-sonnet-5-5',\n 'claude-opus-5-5',\n 'claude-opus-5',\n 'claude-fable-5-1',\n]);\nconst FALLBACK_BETA = 'server-side-fallback-2026-07-01';\n\n// the least thinking each model takes: disabled is a 400 on the newest, and the oldest never think\nexport function thinkingFor(model: string): { type: 'between_tools' | 'disabled' } | undefined {\n if (model === 'claude-sonnet-5-5') return { type: 'between_tools' };\n if (model === 'claude-sonnet-5' || model === 'claude-opus-5') return { type: 'disabled' };\n return undefined;\n}\n\nconst SYSTEM = `You translate UI strings for the Verbaly i18n library.\nRules:\n- Translate only the human-readable text, naturally for the target locale.\n- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.\n- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;\n\nexport function systemPrompt(instructions?: string): string {\n return instructions ? `${SYSTEM}\\n\\nProject instructions:\\n${instructions}` : SYSTEM;\n}\n\nexport function claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n // one client per provider: a batch is a request, not a reason to rebuild the transport\n let client: Promise<InstanceType<typeof import('@anthropic-ai/sdk').default>> | undefined;\n\n return async (request: TranslateRequest) => {\n client ??= loadSdk().then(\n (Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}),\n );\n const model = options.model ?? DEFAULT_MODEL;\n const thinking = thinkingFor(model);\n const response = await (\n await client\n ).beta.messages.create({\n model,\n max_tokens: options.maxTokens ?? 16000,\n ...(thinking && { thinking }),\n ...(FALLBACK_MODELS.has(model) && { betas: [FALLBACK_BETA], fallbacks: 'default' as const }),\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n const batch = counted(Object.keys(request.messages).length, 'message');\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${batch}: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n // a decline is about the content, so asking again gets the same answer: a 400 is never retried\n if (response.stop_reason === 'refusal') {\n const category = response.stop_details?.category;\n throw Object.assign(\n new Error(\n `[verbaly] the model declined a batch of ${batch}${category ? ` (${category})` : ''}, so they stay untranslated: translate them by hand or with another provider`,\n ),\n { status: 400 },\n );\n }\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n try {\n return JSON.parse(text) as Record<string, string>;\n } catch (error) {\n throw new Error('[verbaly] the model did not answer with the JSON object it was asked for', {\n cause: error,\n });\n }\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n return (\n `Translate each value from \"${request.sourceLocale}\" to \"${request.targetLocale}\". ` +\n `Return a JSON object with the same keys and translated values.\\n\\n` +\n JSON.stringify(request.messages, null, 2) +\n glossarySection(request) +\n originsSection(request)\n );\n}\n\n// the glossary is a requirement, not a hint: it exists because a brand name came back translated\nfunction glossarySection(request: TranslateRequest): string {\n const glossary = request.glossary;\n if (!glossary || Object.keys(glossary).length === 0) return '';\n const lines = Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`);\n return `\\n\\nGlossary, these renderings are required wherever the term appears:\\n${lines.join('\\n')}`;\n}\n\nfunction originsSection(request: TranslateRequest): string {\n const origins = request.origins;\n if (!origins || Object.keys(origins).length === 0) return '';\n const lines = Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(', ')}`);\n return `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n${lines.join('\\n')}`;\n}\n\nexport function batchFormat(request: TranslateRequest) {\n const keys = Object.keys(request.messages);\n return {\n type: 'json_schema' as const,\n schema: {\n type: 'object',\n properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),\n required: keys,\n additionalProperties: false,\n },\n };\n}\n\ntype SdkModule = { default: typeof import('@anthropic-ai/sdk').default };\n\n// injectable for tests\nexport async function loadSdk(\n load: () => Promise<SdkModule> = () => import('@anthropic-ai/sdk'),\n): Promise<SdkModule['default']> {\n try {\n const mod = await load();\n return mod.default;\n } catch (error) {\n if (isModuleNotFound(error, '@anthropic-ai/sdk')) {\n throw new Error(\n '[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY',\n { cause: error },\n );\n }\n throw error;\n }\n}\n"],"mappings":";;AAWA,MAAM,gBAAgB;AAGtB,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,gBAAgB;AAGtB,SAAgB,YAAY,OAAmE;CAC7F,I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AAmB,GAC7C,MAAM,IAAI,MACR,mMACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"claude-mvcniUPN.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport { counted } from '../text';\nimport type { TranslateProvider, TranslateRequest } from '../translate';\n\nexport interface ClaudeProviderOptions {\n model?: string;\n apiKey?: string;\n maxTokens?: number;\n}\n\n// balanced default for translation: the current Sonnet, at the price of the one before it\nconst DEFAULT_MODEL = 'claude-sonnet-5-5';\n\n// the models that take fallbacks \"default\": a batch one declines is answered by another model\nconst FALLBACK_MODELS = new Set([\n 'claude-sonnet-5-5',\n 'claude-opus-5-5',\n 'claude-opus-5',\n 'claude-fable-5-1',\n]);\nconst FALLBACK_BETA = 'server-side-fallback-2026-07-01';\n\n// the least thinking each model takes: disabled is a 400 on the newest, and the oldest never think\nexport function thinkingFor(model: string): { type: 'between_tools' | 'disabled' } | undefined {\n if (model === 'claude-sonnet-5-5') return { type: 'between_tools' };\n if (model === 'claude-sonnet-5' || model === 'claude-opus-5') return { type: 'disabled' };\n return undefined;\n}\n\nconst SYSTEM = `You translate UI strings for the Verbaly i18n library.\nRules:\n- Translate only the human-readable text, naturally for the target locale.\n- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.\n- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;\n\nexport function systemPrompt(instructions?: string): string {\n return instructions ? `${SYSTEM}\\n\\nProject instructions:\\n${instructions}` : SYSTEM;\n}\n\nexport function claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n // one client per provider: a batch is a request, not a reason to rebuild the transport\n let client: Promise<InstanceType<typeof import('@anthropic-ai/sdk').default>> | undefined;\n\n return async (request: TranslateRequest) => {\n client ??= loadSdk().then(\n (Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}),\n );\n const model = options.model ?? DEFAULT_MODEL;\n const thinking = thinkingFor(model);\n const response = await (\n await client\n ).beta.messages.create({\n model,\n max_tokens: options.maxTokens ?? 16000,\n ...(thinking && { thinking }),\n ...(FALLBACK_MODELS.has(model) && { betas: [FALLBACK_BETA], fallbacks: 'default' as const }),\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n const batch = counted(Object.keys(request.messages).length, 'message');\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${batch}: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n // a decline is about the content, so asking again gets the same answer: a 400 is never retried\n if (response.stop_reason === 'refusal') {\n const category = response.stop_details?.category;\n throw Object.assign(\n new Error(\n `[verbaly] the model declined a batch of ${batch}${category ? ` (${category})` : ''}, so they stay untranslated: translate them by hand or with another provider`,\n ),\n { status: 400 },\n );\n }\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n try {\n return JSON.parse(text) as Record<string, string>;\n } catch (error) {\n throw new Error('[verbaly] the model did not answer with the JSON object it was asked for', {\n cause: error,\n });\n }\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n return (\n `Translate each value from \"${request.sourceLocale}\" to \"${request.targetLocale}\". ` +\n `Return a JSON object with the same keys and translated values.\\n\\n` +\n JSON.stringify(request.messages, null, 2) +\n glossarySection(request) +\n originsSection(request)\n );\n}\n\n// the glossary is a requirement, not a hint: it exists because a brand name came back translated\nfunction glossarySection(request: TranslateRequest): string {\n const glossary = request.glossary;\n if (!glossary || Object.keys(glossary).length === 0) return '';\n const lines = Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`);\n return `\\n\\nGlossary, these renderings are required wherever the term appears:\\n${lines.join('\\n')}`;\n}\n\nfunction originsSection(request: TranslateRequest): string {\n const origins = request.origins;\n if (!origins || Object.keys(origins).length === 0) return '';\n const lines = Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(', ')}`);\n return `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n${lines.join('\\n')}`;\n}\n\nexport function batchFormat(request: TranslateRequest) {\n const keys = Object.keys(request.messages);\n return {\n type: 'json_schema' as const,\n schema: {\n type: 'object',\n properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),\n required: keys,\n additionalProperties: false,\n },\n };\n}\n\ntype SdkModule = { default: typeof import('@anthropic-ai/sdk').default };\n\n// injectable for tests\nexport async function loadSdk(\n load: () => Promise<SdkModule> = () => import('@anthropic-ai/sdk'),\n): Promise<SdkModule['default']> {\n try {\n const mod = await load();\n return mod.default;\n } catch (error) {\n if (isModuleNotFound(error, '@anthropic-ai/sdk')) {\n throw new Error(\n '[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY',\n { cause: error },\n );\n }\n throw error;\n }\n}\n"],"mappings":";;AAWA,MAAM,gBAAgB;AAGtB,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,gBAAgB;AAGtB,SAAgB,YAAY,OAAmE;CAC7F,IAAI,UAAU,qBAAqB,OAAO,EAAE,MAAM,gBAAgB;CAClE,IAAI,UAAU,qBAAqB,UAAU,iBAAiB,OAAO,EAAE,MAAM,WAAW;AAE1F;AAEA,MAAM,SAAS;;;;;AAMf,SAAgB,aAAa,cAA+B;CAC1D,OAAO,eAAe,GAAG,OAAO,6BAA6B,iBAAiB;AAChF;AAEA,SAAgB,eAAe,UAAiC,CAAC,GAAsB;CAErF,IAAI;CAEJ,OAAO,OAAO,YAA8B;EAC1C,WAAW,QAAQ,CAAC,CAAC,MAClB,cAAc,IAAI,UAAU,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAAC,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