@verbaly/compiler 0.34.0 → 0.36.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 +1 -1
- package/dist/cli.js +98 -3
- package/dist/cli.js.map +1 -1
- package/dist/config-D8gkaunO.js.map +1 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +90 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-D8gkaunO.js","names":[],"sources":["../src/pseudo.ts","../src/config.ts"],"sourcesContent":["import type { Catalog, Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\n\nexport const PSEUDO_LOCALE = 'en-XA';\n\nconst ACCENTS: Record<string, string> = {\n a: 'á',\n b: 'ƀ',\n c: 'ç',\n d: 'đ',\n e: 'é',\n f: 'ƒ',\n g: 'ğ',\n h: 'ĥ',\n i: 'í',\n j: 'ĵ',\n k: 'ķ',\n l: 'ĺ',\n m: 'ɱ',\n n: 'ñ',\n o: 'ó',\n p: 'þ',\n q: 'ǫ',\n r: 'ŕ',\n s: 'š',\n t: 'ţ',\n u: 'ú',\n v: 'ṽ',\n w: 'ŵ',\n x: 'ẋ',\n y: 'ý',\n z: 'ž',\n A: 'Á',\n B: 'Ɓ',\n C: 'Ç',\n D: 'Đ',\n E: 'É',\n F: 'Ƒ',\n G: 'Ğ',\n H: 'Ĥ',\n I: 'Í',\n J: 'Ĵ',\n K: 'Ķ',\n L: 'Ĺ',\n M: 'Ḿ',\n N: 'Ñ',\n O: 'Ó',\n P: 'Þ',\n Q: 'Ǫ',\n R: 'Ŕ',\n S: 'Š',\n T: 'Ţ',\n U: 'Ú',\n V: 'Ṽ',\n W: 'Ŵ',\n X: 'Ẍ',\n Y: 'Ý',\n Z: 'Ž',\n};\n\nconst TAG_AT = /<\\/?[a-zA-Z][\\w-]*\\/?>/y;\n\n// params, variant blocks, tags and escapes survive verbatim\nexport function pseudoLocalize(message: string): string {\n let out = '';\n let letters = 0;\n let i = 0;\n while (i < message.length) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}' || two === '||' || two === '##') {\n out += two;\n i += 2;\n continue;\n }\n const ch = message[i]!;\n if (ch === '{') {\n const end = matchBrace(message, i);\n out += message.slice(i, end);\n i = end;\n continue;\n }\n if (ch === '<') {\n TAG_AT.lastIndex = i;\n const m = TAG_AT.exec(message);\n if (m) {\n out += m[0];\n i += m[0].length;\n continue;\n }\n }\n const mapped = ACCENTS[ch];\n if (mapped) {\n out += mapped;\n letters += 1;\n } else {\n out += ch;\n }\n i += 1;\n }\n const pad = '~'.repeat(Math.ceil(letters / 3));\n return `⟦${out}${pad ? ' ' + pad : ''}⟧`;\n}\n\nfunction matchBrace(message: string, start: number): number {\n let depth = 0;\n for (let i = start; i < message.length; i++) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}') {\n i += 1;\n continue;\n }\n const ch = message[i];\n if (ch === '{') depth += 1;\n else if (ch === '}') {\n depth -= 1;\n if (depth === 0) return i + 1;\n }\n }\n return message.length; // unbalanced → verbatim\n}\n\n// regenerates the whole pseudo catalog from the source catalog\nexport function pseudoCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n locale: string = PSEUDO_LOCALE,\n): string[] {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const target: Catalog = {};\n for (const [key, msg] of Object.entries(source)) {\n target[key] = msg ? pseudoLocalize(msg) : '';\n }\n catalogs[locale] = target;\n return Object.keys(target).filter((key) => target[key]);\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { RichLink } from 'verbaly';\nimport { PSEUDO_LOCALE } from './pseudo';\nimport type { TranslateProvider } from './translate';\n\nexport interface TranslateConfig {\n provider?: 'claude' | TranslateProvider;\n model?: string;\n batchSize?: number;\n}\n\nexport interface RenderConfig {\n links?: Record<string, RichLink>;\n site?: string;\n attribute?: string;\n baseUrl?: string;\n hreflang?: boolean;\n sitemap?: boolean | string;\n clean?: boolean;\n}\n\nexport interface VerbalyConfig {\n root?: string;\n dir?: string;\n sourceLocale?: string;\n locales?: string[];\n include?: string[];\n exclude?: string[];\n dts?: string | false;\n translate?: TranslateConfig;\n render?: RenderConfig;\n}\n\nexport interface ResolvedConfig {\n root: string;\n dir: string;\n sourceLocale: string;\n locales: string[];\n include: string[];\n exclude: string[];\n dts: string | false | undefined;\n translate: TranslateConfig;\n render: RenderConfig;\n}\n\nexport function resolveConfig(config: VerbalyConfig = {}): ResolvedConfig {\n const root = resolve(config.root ?? process.cwd());\n const dir = resolve(root, config.dir ?? 'locales');\n const sourceLocale = config.sourceLocale ?? 'en';\n\n const locales = new Set<string>([sourceLocale, ...(config.locales ?? [])]);\n if (existsSync(dir)) {\n for (const file of readdirSync(dir)) {\n if (file.endsWith('.json') && !file.startsWith('.') && file !== `${PSEUDO_LOCALE}.json`) {\n locales.add(file.slice(0, -5));\n }\n }\n }\n\n return {\n root,\n dir,\n sourceLocale,\n locales: [...locales],\n include: config.include ?? ['{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}'],\n exclude: config.exclude ?? ['**/node_modules/**', '**/dist/**'],\n dts: typeof config.dts === 'string' ? resolve(root, config.dts) : config.dts,\n translate: config.translate ?? {},\n render: config.render ?? {},\n };\n}\n\nconst CONFIG_FILES = [\n 'verbaly.config.js',\n 'verbaly.config.mjs',\n 'verbaly.config.ts',\n 'verbaly.config.mts',\n 'verbaly.config.json',\n];\n\nexport function findConfigFile(root: string): string | undefined {\n return CONFIG_FILES.find((name) => existsSync(join(root, name)));\n}\n\nexport async function loadConfigFile(root: string): Promise<VerbalyConfig> {\n for (const name of ['verbaly.config.js', 'verbaly.config.mjs']) {\n const path = join(root, name);\n if (existsSync(path)) {\n const mod = (await import(pathToFileURL(path).href)) as { default?: VerbalyConfig };\n return mod.default ?? {};\n }\n }\n for (const name of ['verbaly.config.ts', 'verbaly.config.mts']) {\n const path = join(root, name);\n if (existsSync(path)) return loadTsConfig(path);\n }\n const jsonPath = join(root, 'verbaly.config.json');\n if (existsSync(jsonPath)) {\n return JSON.parse(readFileSync(jsonPath, 'utf8')) as VerbalyConfig;\n }\n return {};\n}\n\nasync function loadTsConfig(path: string): Promise<VerbalyConfig> {\n try {\n const { bundleRequire } = await import('bundle-require');\n const { mod } = await bundleRequire<{ default?: VerbalyConfig }>({ filepath: path });\n return mod.default ?? {};\n } catch (error) {\n if (isModuleNotFound(error, 'esbuild')) {\n throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, {\n cause: error,\n });\n }\n throw error;\n }\n}\n\nexport function isModuleNotFound(error: unknown, name: string): boolean {\n return (\n error instanceof Error &&\n (error as { code?: string }).code === 'ERR_MODULE_NOT_FOUND' &&\n error.message.includes(name)\n );\n}\n\n// non-source locales a command may write to (optional CLI override, always config-bounded)\nexport function targetLocales(cfg: ResolvedConfig, override?: string[]): string[] {\n return (override ?? cfg.locales).filter(\n (locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale),\n );\n}\n\n// file config + inline overrides\nexport async function loadConfig(\n root: string,\n overrides: VerbalyConfig = {},\n): Promise<ResolvedConfig> {\n const fileConfig = await loadConfigFile(root);\n return resolveConfig({ ...fileConfig, ...definedOnly(overrides), root });\n}\n\nfunction definedOnly(config: VerbalyConfig): VerbalyConfig {\n return Object.fromEntries(\n Object.entries(config).filter(([, value]) => value !== undefined),\n ) as VerbalyConfig;\n}\n"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"config-D8gkaunO.js","names":[],"sources":["../src/pseudo.ts","../src/config.ts"],"sourcesContent":["import type { Catalog, Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\n\nexport const PSEUDO_LOCALE = 'en-XA';\n\nconst ACCENTS: Record<string, string> = {\n a: 'á',\n b: 'ƀ',\n c: 'ç',\n d: 'đ',\n e: 'é',\n f: 'ƒ',\n g: 'ğ',\n h: 'ĥ',\n i: 'í',\n j: 'ĵ',\n k: 'ķ',\n l: 'ĺ',\n m: 'ɱ',\n n: 'ñ',\n o: 'ó',\n p: 'þ',\n q: 'ǫ',\n r: 'ŕ',\n s: 'š',\n t: 'ţ',\n u: 'ú',\n v: 'ṽ',\n w: 'ŵ',\n x: 'ẋ',\n y: 'ý',\n z: 'ž',\n A: 'Á',\n B: 'Ɓ',\n C: 'Ç',\n D: 'Đ',\n E: 'É',\n F: 'Ƒ',\n G: 'Ğ',\n H: 'Ĥ',\n I: 'Í',\n J: 'Ĵ',\n K: 'Ķ',\n L: 'Ĺ',\n M: 'Ḿ',\n N: 'Ñ',\n O: 'Ó',\n P: 'Þ',\n Q: 'Ǫ',\n R: 'Ŕ',\n S: 'Š',\n T: 'Ţ',\n U: 'Ú',\n V: 'Ṽ',\n W: 'Ŵ',\n X: 'Ẍ',\n Y: 'Ý',\n Z: 'Ž',\n};\n\nconst TAG_AT = /<\\/?[a-zA-Z][\\w-]*\\/?>/y;\n\n// params, variant blocks, tags and escapes survive verbatim\nexport function pseudoLocalize(message: string): string {\n let out = '';\n let letters = 0;\n let i = 0;\n while (i < message.length) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}' || two === '||' || two === '##') {\n out += two;\n i += 2;\n continue;\n }\n const ch = message[i]!;\n if (ch === '{') {\n const end = matchBrace(message, i);\n out += message.slice(i, end);\n i = end;\n continue;\n }\n if (ch === '<') {\n TAG_AT.lastIndex = i;\n const m = TAG_AT.exec(message);\n if (m) {\n out += m[0];\n i += m[0].length;\n continue;\n }\n }\n const mapped = ACCENTS[ch];\n if (mapped) {\n out += mapped;\n letters += 1;\n } else {\n out += ch;\n }\n i += 1;\n }\n const pad = '~'.repeat(Math.ceil(letters / 3));\n return `⟦${out}${pad ? ' ' + pad : ''}⟧`;\n}\n\nfunction matchBrace(message: string, start: number): number {\n let depth = 0;\n for (let i = start; i < message.length; i++) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}') {\n i += 1;\n continue;\n }\n const ch = message[i];\n if (ch === '{') depth += 1;\n else if (ch === '}') {\n depth -= 1;\n if (depth === 0) return i + 1;\n }\n }\n return message.length; // unbalanced → verbatim\n}\n\n// regenerates the whole pseudo catalog from the source catalog\nexport function pseudoCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n locale: string = PSEUDO_LOCALE,\n): string[] {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const target: Catalog = {};\n for (const [key, msg] of Object.entries(source)) {\n target[key] = msg ? pseudoLocalize(msg) : '';\n }\n catalogs[locale] = target;\n return Object.keys(target).filter((key) => target[key]);\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { RichLink } from 'verbaly';\nimport { PSEUDO_LOCALE } from './pseudo';\nimport type { TranslateProvider } from './translate';\n\nexport interface TranslateConfig {\n provider?: 'claude' | TranslateProvider;\n model?: string;\n batchSize?: number;\n}\n\nexport interface RedirectConfig {\n on?: 'root' | 'all';\n storageKey?: string | false;\n}\n\nexport interface RenderConfig {\n links?: Record<string, RichLink>;\n site?: string;\n attribute?: string;\n base?: string;\n baseUrl?: string;\n hreflang?: boolean;\n sitemap?: boolean | string;\n redirect?: boolean | RedirectConfig;\n clean?: boolean;\n}\n\nexport interface VerbalyConfig {\n root?: string;\n dir?: string;\n sourceLocale?: string;\n locales?: string[];\n include?: string[];\n exclude?: string[];\n dts?: string | false;\n translate?: TranslateConfig;\n render?: RenderConfig;\n}\n\nexport interface ResolvedConfig {\n root: string;\n dir: string;\n sourceLocale: string;\n locales: string[];\n include: string[];\n exclude: string[];\n dts: string | false | undefined;\n translate: TranslateConfig;\n render: RenderConfig;\n}\n\nexport function resolveConfig(config: VerbalyConfig = {}): ResolvedConfig {\n const root = resolve(config.root ?? process.cwd());\n const dir = resolve(root, config.dir ?? 'locales');\n const sourceLocale = config.sourceLocale ?? 'en';\n\n const locales = new Set<string>([sourceLocale, ...(config.locales ?? [])]);\n if (existsSync(dir)) {\n for (const file of readdirSync(dir)) {\n if (file.endsWith('.json') && !file.startsWith('.') && file !== `${PSEUDO_LOCALE}.json`) {\n locales.add(file.slice(0, -5));\n }\n }\n }\n\n return {\n root,\n dir,\n sourceLocale,\n locales: [...locales],\n include: config.include ?? ['{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}'],\n exclude: config.exclude ?? ['**/node_modules/**', '**/dist/**'],\n dts: typeof config.dts === 'string' ? resolve(root, config.dts) : config.dts,\n translate: config.translate ?? {},\n render: config.render ?? {},\n };\n}\n\nconst CONFIG_FILES = [\n 'verbaly.config.js',\n 'verbaly.config.mjs',\n 'verbaly.config.ts',\n 'verbaly.config.mts',\n 'verbaly.config.json',\n];\n\nexport function findConfigFile(root: string): string | undefined {\n return CONFIG_FILES.find((name) => existsSync(join(root, name)));\n}\n\nexport async function loadConfigFile(root: string): Promise<VerbalyConfig> {\n for (const name of ['verbaly.config.js', 'verbaly.config.mjs']) {\n const path = join(root, name);\n if (existsSync(path)) {\n const mod = (await import(pathToFileURL(path).href)) as { default?: VerbalyConfig };\n return mod.default ?? {};\n }\n }\n for (const name of ['verbaly.config.ts', 'verbaly.config.mts']) {\n const path = join(root, name);\n if (existsSync(path)) return loadTsConfig(path);\n }\n const jsonPath = join(root, 'verbaly.config.json');\n if (existsSync(jsonPath)) {\n return JSON.parse(readFileSync(jsonPath, 'utf8')) as VerbalyConfig;\n }\n return {};\n}\n\nasync function loadTsConfig(path: string): Promise<VerbalyConfig> {\n try {\n const { bundleRequire } = await import('bundle-require');\n const { mod } = await bundleRequire<{ default?: VerbalyConfig }>({ filepath: path });\n return mod.default ?? {};\n } catch (error) {\n if (isModuleNotFound(error, 'esbuild')) {\n throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, {\n cause: error,\n });\n }\n throw error;\n }\n}\n\nexport function isModuleNotFound(error: unknown, name: string): boolean {\n return (\n error instanceof Error &&\n (error as { code?: string }).code === 'ERR_MODULE_NOT_FOUND' &&\n error.message.includes(name)\n );\n}\n\n// non-source locales a command may write to (optional CLI override, always config-bounded)\nexport function targetLocales(cfg: ResolvedConfig, override?: string[]): string[] {\n return (override ?? cfg.locales).filter(\n (locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale),\n );\n}\n\n// file config + inline overrides\nexport async function loadConfig(\n root: string,\n overrides: VerbalyConfig = {},\n): Promise<ResolvedConfig> {\n const fileConfig = await loadConfigFile(root);\n return resolveConfig({ ...fileConfig, ...definedOnly(overrides), root });\n}\n\nfunction definedOnly(config: VerbalyConfig): VerbalyConfig {\n return Object.fromEntries(\n Object.entries(config).filter(([, value]) => value !== undefined),\n ) as VerbalyConfig;\n}\n"],"mappings":";;;;;ACsDA,SAAgB,cAAc,SAAwB,CAAC,GAAmB;CACxE,MAAM,OAAO,QAAQ,OAAO,QAAQ,QAAQ,IAAI,CAAC;CACjD,MAAM,MAAM,QAAQ,MAAM,OAAO,OAAO,SAAS;CACjD,MAAM,eAAe,OAAO,gBAAgB;CAE5C,MAAM,0BAAU,IAAI,IAAY,CAAC,cAAc,GAAI,OAAO,WAAW,CAAC,CAAE,CAAC;CACzE,IAAI,WAAW,GAAG,GACX;OAAA,MAAM,QAAQ,YAAY,GAAG,GAChC,IAAI,KAAK,SAAS,OAAO,KAAK,CAAC,KAAK,WAAW,GAAG,KAAK,SAAS,cAC9D,QAAQ,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC;CAAA;CAKnC,OAAO;EACL;EACA;EACA;EACA,SAAS,CAAC,GAAG,OAAO;EACpB,SAAS,OAAO,WAAW,CAAC,yDAAyD;EACrF,SAAS,OAAO,WAAW,CAAC,sBAAsB,YAAY;EAC9D,KAAK,OAAO,OAAO,QAAQ,WAAW,QAAQ,MAAM,OAAO,GAAG,IAAI,OAAO;EACzE,WAAW,OAAO,aAAa,CAAC;EAChC,QAAQ,OAAO,UAAU,CAAC;CAC5B;AACF;AAcA,eAAsB,eAAe,MAAsC;CACzE,KAAK,MAAM,QAAQ,CAAC,qBAAqB,oBAAoB,GAAG;EAC9D,MAAM,OAAO,KAAK,MAAM,IAAI;EAC5B,IAAI,WAAW,IAAI,GAEjB,QAAO,MADY,OAAO,cAAc,IAAI,CAAC,CAAC,MAAA,CACnC,WAAW,CAAC;CAE3B;CACA,KAAK,MAAM,QAAQ,CAAC,qBAAqB,oBAAoB,GAAG;EAC9D,MAAM,OAAO,KAAK,MAAM,IAAI;EAC5B,IAAI,WAAW,IAAI,GAAG,OAAO,aAAa,IAAI;CAChD;CACA,MAAM,WAAW,KAAK,MAAM,qBAAqB;CACjD,IAAI,WAAW,QAAQ,GACrB,OAAO,KAAK,MAAM,aAAa,UAAU,MAAM,CAAC;CAElD,OAAO,CAAC;AACV;AAEA,eAAe,aAAa,MAAsC;CAChE,IAAI;EACF,MAAM,EAAE,kBAAkB,MAAM,OAAO;EACvC,MAAM,EAAE,QAAQ,MAAM,cAA2C,EAAE,UAAU,KAAK,CAAC;EACnF,OAAO,IAAI,WAAW,CAAC;CACzB,SAAS,OAAO;EACd,IAAI,iBAAiB,OAAO,SAAS,GACnC,MAAM,IAAI,MAAM,aAAa,KAAK,sDAAsD,EACtF,OAAO,MACT,CAAC;EAEH,MAAM;CACR;AACF;AAEA,SAAgB,iBAAiB,OAAgB,MAAuB;CACtE,OACE,iBAAiB,SAChB,MAA4B,SAAS,0BACtC,MAAM,QAAQ,SAAS,IAAI;AAE/B;AAGA,SAAgB,cAAc,KAAqB,UAA+B;CAChF,QAAQ,YAAY,IAAI,QAAA,CAAS,QAC9B,WAAW,WAAW,IAAI,gBAAgB,IAAI,QAAQ,SAAS,MAAM,CACxE;AACF;AAGA,eAAsB,WACpB,MACA,YAA2B,CAAC,GACH;CAEzB,OAAO,cAAc;EAAE,GAAG,MADD,eAAe,IAAI;EACN,GAAG,YAAY,SAAS;EAAG;CAAK,CAAC;AACzE;AAEA,SAAS,YAAY,QAAsC;CACzD,OAAO,OAAO,YACZ,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CAClE;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -34,13 +34,19 @@ interface TranslateConfig {
|
|
|
34
34
|
model?: string;
|
|
35
35
|
batchSize?: number;
|
|
36
36
|
}
|
|
37
|
+
interface RedirectConfig {
|
|
38
|
+
on?: 'root' | 'all';
|
|
39
|
+
storageKey?: string | false;
|
|
40
|
+
}
|
|
37
41
|
interface RenderConfig {
|
|
38
42
|
links?: Record<string, RichLink>;
|
|
39
43
|
site?: string;
|
|
40
44
|
attribute?: string;
|
|
45
|
+
base?: string;
|
|
41
46
|
baseUrl?: string;
|
|
42
47
|
hreflang?: boolean;
|
|
43
48
|
sitemap?: boolean | string;
|
|
49
|
+
redirect?: boolean | RedirectConfig;
|
|
44
50
|
clean?: boolean;
|
|
45
51
|
}
|
|
46
52
|
interface VerbalyConfig {
|
|
@@ -229,9 +235,11 @@ interface RenderSiteOptions {
|
|
|
229
235
|
attribute?: string;
|
|
230
236
|
richTags?: string[];
|
|
231
237
|
richLinks?: Record<string, RichLink>;
|
|
238
|
+
base?: string;
|
|
232
239
|
baseUrl?: string;
|
|
233
240
|
hreflang?: boolean;
|
|
234
241
|
sitemap?: boolean | string;
|
|
242
|
+
redirect?: boolean | RedirectConfig;
|
|
235
243
|
clean?: boolean;
|
|
236
244
|
}
|
|
237
245
|
interface RenderSiteResult {
|
|
@@ -241,5 +249,5 @@ interface RenderSiteResult {
|
|
|
241
249
|
}
|
|
242
250
|
declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
|
|
243
251
|
//#endregion
|
|
244
|
-
export { type BrokenEntry, type Catalog, type Catalogs, type CheckResult, type Drafts, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type PluginOptions, RESOLVED_VIRTUAL_ID, type RenderConfig, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SOURCE_FILE_RE, type StatusResult, type SyncResult, type TransformResult, type TranslateConfig, type TranslateOptions, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type VerbalyConfig, check, collectOrigins, createSourceFilter, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatStatusResult, generateDts, generateLocaleModule, generateRuntimeModule, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, writeCatalog, writeDts };
|
|
252
|
+
export { type BrokenEntry, type Catalog, type Catalogs, type CheckResult, type Drafts, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type PluginOptions, RESOLVED_VIRTUAL_ID, type RedirectConfig, type RenderConfig, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SOURCE_FILE_RE, type StatusResult, type SyncResult, type TransformResult, type TranslateConfig, type TranslateOptions, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type VerbalyConfig, check, collectOrigins, createSourceFilter, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatStatusResult, generateDts, generateLocaleModule, generateRuntimeModule, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, writeCatalog, writeDts };
|
|
245
253
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { dirname, join, relative } from "node:path";
|
|
|
4
4
|
import { glob } from "tinyglobby";
|
|
5
5
|
import { parse } from "@babel/parser";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
|
-
import { RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
|
|
7
|
+
import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse as parse$1, parseTags, safeAttribute } from "verbaly";
|
|
8
8
|
import picomatch from "picomatch";
|
|
9
9
|
import MagicString from "magic-string";
|
|
10
10
|
//#region src/catalog.ts
|
|
@@ -1252,6 +1252,8 @@ function structureMatches(source, translated) {
|
|
|
1252
1252
|
//#region src/render.ts
|
|
1253
1253
|
const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
|
|
1254
1254
|
const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
|
|
1255
|
+
const REDIRECT_OPEN = "<!--verbaly:redirect-->";
|
|
1256
|
+
const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
|
|
1255
1257
|
const VOID = new Set(VOID_TAGS);
|
|
1256
1258
|
const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
|
|
1257
1259
|
const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
|
@@ -1274,13 +1276,15 @@ function renderHtml(html, options) {
|
|
|
1274
1276
|
const missing = /* @__PURE__ */ new Set();
|
|
1275
1277
|
const skip = protectedRanges(html);
|
|
1276
1278
|
const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
|
|
1279
|
+
const filled = [];
|
|
1280
|
+
const inFilled = (index) => filled.some(([from, to]) => index >= from && index < to);
|
|
1277
1281
|
const selfUrl = options.alternates?.find((a) => a.hreflang === options.locale)?.href;
|
|
1278
1282
|
const sourceUrl = options.alternates?.find((a) => a.hreflang === "x-default")?.href;
|
|
1279
1283
|
const rewriteUrl = selfUrl !== void 0 && selfUrl !== sourceUrl;
|
|
1280
1284
|
START_TAG.lastIndex = 0;
|
|
1281
1285
|
let m;
|
|
1282
1286
|
while ((m = START_TAG.exec(html)) !== null) {
|
|
1283
|
-
if (inSkip(m.index)) continue;
|
|
1287
|
+
if (inSkip(m.index) || inFilled(m.index)) continue;
|
|
1284
1288
|
const [full, rawName, attrChunk] = m;
|
|
1285
1289
|
const tagName = rawName.toLowerCase();
|
|
1286
1290
|
const openEnd = m.index + full.length;
|
|
@@ -1293,6 +1297,18 @@ function renderHtml(html, options) {
|
|
|
1293
1297
|
const attrs = parseAttrs(attrChunk);
|
|
1294
1298
|
if (rewriteUrl && tagName === "link" && attrs.get("rel")?.toLowerCase() === "canonical" && decodeEntities(attrs.get("href") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", selfUrl);
|
|
1295
1299
|
if (rewriteUrl && tagName === "meta" && attrs.get("property") === "og:url" && decodeEntities(attrs.get("content") ?? "") === sourceUrl) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", selfUrl);
|
|
1300
|
+
const mirror = options.mirror;
|
|
1301
|
+
if (mirror) {
|
|
1302
|
+
if (tagName === "a" || tagName === "area") {
|
|
1303
|
+
const inside = mirroredHref(attrs.get("href"), mirror);
|
|
1304
|
+
if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "href", inside);
|
|
1305
|
+
} else if (tagName === "meta" && attrs.get("http-equiv")?.toLowerCase() === "refresh") {
|
|
1306
|
+
const content = attrs.get("content") ?? "";
|
|
1307
|
+
const url = /^([^;]*;\s*url\s*=\s*)(.*)$/i.exec(decodeEntities(content));
|
|
1308
|
+
const inside = url && mirroredHref(url[2], mirror);
|
|
1309
|
+
if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, "content", `${url[1]}${inside}`);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1296
1312
|
const key = attrs.get(attr);
|
|
1297
1313
|
const attrMapRaw = attrs.get(attrsAttr);
|
|
1298
1314
|
if (key === void 0 && attrMapRaw === void 0) continue;
|
|
@@ -1311,6 +1327,7 @@ function renderHtml(html, options) {
|
|
|
1311
1327
|
const content = attrs.has(richAttr) ? richToHtml(parseTags(text), richTags, links) : escapeHtml(text);
|
|
1312
1328
|
if (html.slice(openEnd, close.contentEnd) !== content) if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);
|
|
1313
1329
|
else ms.overwrite(openEnd, close.contentEnd, content);
|
|
1330
|
+
filled.push([openEnd, close.contentEnd]);
|
|
1314
1331
|
}
|
|
1315
1332
|
}
|
|
1316
1333
|
}
|
|
@@ -1328,11 +1345,64 @@ function renderHtml(html, options) {
|
|
|
1328
1345
|
}
|
|
1329
1346
|
}
|
|
1330
1347
|
if (options.alternates?.length) injectAlternates(ms, html, options.alternates);
|
|
1348
|
+
if (options.redirect) injectRedirect(ms, html, options.redirect);
|
|
1331
1349
|
return {
|
|
1332
1350
|
html: ms.toString(),
|
|
1333
1351
|
missing: [...missing]
|
|
1334
1352
|
};
|
|
1335
1353
|
}
|
|
1354
|
+
function publicPath(rel) {
|
|
1355
|
+
const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
|
|
1356
|
+
return path.length > 1 ? path.replace(/\/+$/, "") : path;
|
|
1357
|
+
}
|
|
1358
|
+
function mirroredHref(raw, mirror) {
|
|
1359
|
+
if (raw === void 0) return void 0;
|
|
1360
|
+
const href = decodeEntities(raw);
|
|
1361
|
+
if (!href.startsWith("/") || href.startsWith("//")) return void 0;
|
|
1362
|
+
const base = mirror.base ?? "";
|
|
1363
|
+
const inside = base ? stripBase(href, base) : href;
|
|
1364
|
+
if (base && inside === href) return void 0;
|
|
1365
|
+
const cut = inside.search(/[?#]/);
|
|
1366
|
+
const path = cut < 0 ? inside : inside.slice(0, cut);
|
|
1367
|
+
if (!mirror.pages.has(publicPath(path.replace(/^\//, "")))) return void 0;
|
|
1368
|
+
return `${base}${mirror.prefix}${inside}`;
|
|
1369
|
+
}
|
|
1370
|
+
function stripBase(path, base) {
|
|
1371
|
+
if (!path.startsWith(base)) return path;
|
|
1372
|
+
const rest = path.slice(base.length);
|
|
1373
|
+
if (rest === "") return "/";
|
|
1374
|
+
return rest.startsWith("/") ? rest : path;
|
|
1375
|
+
}
|
|
1376
|
+
function normalizeBase(base) {
|
|
1377
|
+
const trimmed = base?.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
1378
|
+
return trimmed ? `/${trimmed}` : "";
|
|
1379
|
+
}
|
|
1380
|
+
const REDIRECT_BODY = "(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}var p=location.pathname;if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}if(M(p.split(\"/\")[1],1))return;var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}if(!w||w===D)return;location.replace(B+\"/\"+w+p+location.search+location.hash)})()";
|
|
1381
|
+
function jsLiteral(value) {
|
|
1382
|
+
return JSON.stringify(value ?? null).replace(/</g, "\\u003c");
|
|
1383
|
+
}
|
|
1384
|
+
function redirectScript(options) {
|
|
1385
|
+
return `<script>var ${[
|
|
1386
|
+
`S=${jsLiteral(options.locales)}`,
|
|
1387
|
+
`D=${jsLiteral(options.sourceLocale)}`,
|
|
1388
|
+
`B=${jsLiteral(normalizeBase(options.base))}`,
|
|
1389
|
+
`K=${options.storageKey === false ? "null" : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`
|
|
1390
|
+
].join(",")};${REDIRECT_BODY};<\/script>`;
|
|
1391
|
+
}
|
|
1392
|
+
function injectRedirect(ms, html, options) {
|
|
1393
|
+
const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;
|
|
1394
|
+
const from = html.indexOf(REDIRECT_OPEN);
|
|
1395
|
+
if (from !== -1) {
|
|
1396
|
+
const to = html.indexOf(REDIRECT_CLOSE, from);
|
|
1397
|
+
if (to !== -1) {
|
|
1398
|
+
const end = to + 24;
|
|
1399
|
+
if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
const head = /<head\b(?:"[^"]*"|'[^']*'|[^"'>])*>/i.exec(html);
|
|
1404
|
+
if (head) ms.appendRight(head.index + head[0].length, block);
|
|
1405
|
+
}
|
|
1336
1406
|
function injectAlternates(ms, html, alternates) {
|
|
1337
1407
|
const links = alternates.map((a) => `<link rel="alternate" hreflang="${escapeAttr(a.hreflang)}" href="${escapeAttr(a.href)}">`).join("");
|
|
1338
1408
|
const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;
|
|
@@ -1352,11 +1422,20 @@ async function renderSite(cfg, options = {}) {
|
|
|
1352
1422
|
const site = join(cfg.root, options.site ?? cfg.render.site ?? "dist");
|
|
1353
1423
|
const locales = options.locales ?? cfg.locales;
|
|
1354
1424
|
const attribute = options.attribute ?? cfg.render.attribute;
|
|
1425
|
+
const base = normalizeBase(options.base ?? cfg.render.base);
|
|
1355
1426
|
const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\/+$/, "");
|
|
1356
1427
|
const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== void 0;
|
|
1357
1428
|
const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;
|
|
1358
1429
|
const wantSitemap = sitemap !== false && baseUrl !== void 0;
|
|
1359
1430
|
const clean = options.clean ?? cfg.render.clean ?? false;
|
|
1431
|
+
const wanted = options.redirect ?? cfg.render.redirect ?? false;
|
|
1432
|
+
const redirect = wanted === false ? void 0 : wanted === true ? {} : wanted;
|
|
1433
|
+
const script = redirect && {
|
|
1434
|
+
locales,
|
|
1435
|
+
sourceLocale: cfg.sourceLocale,
|
|
1436
|
+
base,
|
|
1437
|
+
storageKey: redirect.storageKey
|
|
1438
|
+
};
|
|
1360
1439
|
const catalogs = loadCatalogs(cfg);
|
|
1361
1440
|
if (clean) {
|
|
1362
1441
|
for (const locale of locales) if (locale !== cfg.sourceLocale) rmSync(join(site, locale), {
|
|
@@ -1369,6 +1448,7 @@ async function renderSite(cfg, options = {}) {
|
|
|
1369
1448
|
absolute: true,
|
|
1370
1449
|
ignore: locales.map((locale) => `${locale}/**`)
|
|
1371
1450
|
});
|
|
1451
|
+
const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\/g, "/"))));
|
|
1372
1452
|
const missing = {};
|
|
1373
1453
|
const urls = [];
|
|
1374
1454
|
for (const file of files) {
|
|
@@ -1379,6 +1459,7 @@ async function renderSite(cfg, options = {}) {
|
|
|
1379
1459
|
rel,
|
|
1380
1460
|
alternates
|
|
1381
1461
|
});
|
|
1462
|
+
const routed = script && (redirect.on === "all" || rel === "index.html");
|
|
1382
1463
|
for (const locale of locales) {
|
|
1383
1464
|
const result = renderHtml(html, {
|
|
1384
1465
|
locale,
|
|
@@ -1387,7 +1468,13 @@ async function renderSite(cfg, options = {}) {
|
|
|
1387
1468
|
attribute,
|
|
1388
1469
|
richTags: options.richTags,
|
|
1389
1470
|
richLinks: options.richLinks ?? cfg.render.links,
|
|
1390
|
-
alternates
|
|
1471
|
+
alternates,
|
|
1472
|
+
mirror: locale === cfg.sourceLocale ? void 0 : {
|
|
1473
|
+
prefix: `/${locale}`,
|
|
1474
|
+
base,
|
|
1475
|
+
pages
|
|
1476
|
+
},
|
|
1477
|
+
redirect: routed && locale === cfg.sourceLocale ? script : void 0
|
|
1391
1478
|
});
|
|
1392
1479
|
for (const key of result.missing) {
|
|
1393
1480
|
const list = missing[locale] ??= [];
|