@intlayer/svelte-compiler 8.1.2 → 8.1.3

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,240 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- let node_module = require("node:module");
3
- let node_path = require("node:path");
4
- let _intlayer_babel = require("@intlayer/babel");
5
- let _intlayer_chokidar = require("@intlayer/chokidar");
6
- let _intlayer_config = require("@intlayer/config");
7
-
8
- //#region src/SvelteIntlayerCompiler.ts
9
- /**
10
- * Create a SvelteIntlayerCompiler - A Vite-compatible compiler plugin for Svelte with Intlayer
11
- *
12
- * Handles Svelte components with special handling for:
13
- * - Script blocks in .svelte files
14
- * - TypeScript in Svelte files
15
- * - Svelte-specific transformations
16
- *
17
- * @example
18
- * ```ts
19
- * // vite.config.ts
20
- * import { defineConfig } from 'vite';
21
- * import { svelte } from '@sveltejs/vite-plugin-svelte';
22
- * import { svelteIntlayerCompiler } from '@intlayer/svelte-compiler';
23
- *
24
- * export default defineConfig({
25
- * plugins: [svelte(), svelteIntlayerCompiler()],
26
- * });
27
- * ```
28
- */
29
- const createSvelteIntlayerCompiler = (options) => {
30
- const pluginName = "svelte-intlayer-compiler";
31
- let config;
32
- let logger;
33
- let projectRoot = "";
34
- let mode = "dev";
35
- let hmrVersion = -1;
36
- const lastSourceTriggeredWrite = 0;
37
- let filesList = [];
38
- let babel = null;
39
- const dictionaryModeMap = {};
40
- const configOptions = options?.configOptions;
41
- const customCompilerConfig = options?.compilerConfig;
42
- /**
43
- * Build the list of files to transform based on configuration patterns
44
- * Includes Svelte-specific patterns
45
- */
46
- const buildFilesListFn = async () => {
47
- const { traversePattern } = config.build;
48
- const { baseDir, fileExtensions, codeDir } = config.content;
49
- const { mainDir } = config.system;
50
- const filesListPattern = Array.from(new Set([baseDir, ...codeDir])).flatMap((root) => (0, _intlayer_chokidar.buildFilesList)({
51
- transformPattern: customCompilerConfig?.transformPattern ?? traversePattern,
52
- excludePattern: [
53
- ...customCompilerConfig?.excludePattern ?? [],
54
- "**/node_modules/**",
55
- ...fileExtensions.map((pattern) => `**/*${pattern}`)
56
- ],
57
- baseDir: root
58
- }));
59
- const dictionariesEntryPath = (0, node_path.join)(mainDir, "dictionaries.mjs");
60
- const unmergedDictionariesEntryPath = (0, node_path.join)(mainDir, "unmerged_dictionaries.mjs");
61
- filesList = [...new Set([
62
- ...filesListPattern,
63
- dictionariesEntryPath,
64
- unmergedDictionariesEntryPath
65
- ])];
66
- };
67
- /**
68
- * Load dictionary keys that have specific import modes
69
- */
70
- const loadDictionaryModeMap = async () => {
71
- try {
72
- const { getDictionaries } = await import("@intlayer/dictionaries-entry");
73
- const dictionaries = getDictionaries();
74
- Object.values(dictionaries).forEach((dictionary) => {
75
- dictionaryModeMap[dictionary.key] = dictionary.importMode ?? config.build.importMode;
76
- });
77
- } catch {}
78
- };
79
- /**
80
- * Initialize the compiler with the given mode
81
- */
82
- const init = async (compilerMode) => {
83
- mode = compilerMode;
84
- config = (0, _intlayer_config.getConfiguration)(configOptions);
85
- logger = (0, _intlayer_config.getAppLogger)(config);
86
- try {
87
- babel = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("@babel/core");
88
- } catch {
89
- logger("Failed to load @babel/core. Transformation will be disabled.", { level: "warn" });
90
- }
91
- await buildFilesListFn();
92
- await loadDictionaryModeMap();
93
- };
94
- /**
95
- * Vite hook: configResolved
96
- */
97
- const configResolved = async (viteConfig) => {
98
- const compilerMode = viteConfig.env?.DEV ? "dev" : "build";
99
- projectRoot = viteConfig.root;
100
- await init(compilerMode);
101
- };
102
- /**
103
- * Prepare intlayer dictionaries and types
104
- */
105
- const buildStart = async () => {
106
- const isBuild = mode === "build";
107
- await (0, _intlayer_chokidar.prepareIntlayer)(config, {
108
- clean: isBuild,
109
- cacheTimeoutMs: isBuild ? 1e3 * 30 : 1e3 * 60 * 60
110
- });
111
- };
112
- /**
113
- * Configure the dev server with file watching
114
- */
115
- const configureServer = async () => {
116
- if (config.content.watch) (0, _intlayer_chokidar.watch)({ configuration: config });
117
- };
118
- /**
119
- * Handle HMR for content changes
120
- */
121
- const handleHotUpdate = async (ctx) => {
122
- const { file, server } = ctx;
123
- if (!config.content.watchedFilesPatternWithPath.some((pattern) => {
124
- return new RegExp(pattern.replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*")).test(file);
125
- })) {
126
- const dictionariesDir = config.system.dictionariesDir;
127
- if (file.startsWith(dictionariesDir)) return [];
128
- hmrVersion++;
129
- return;
130
- }
131
- if (!(performance.now() - lastSourceTriggeredWrite < 1e3)) {
132
- server.ws.send({ type: "full-reload" });
133
- return [];
134
- }
135
- };
136
- /**
137
- * Transform handler with Svelte-specific handling
138
- */
139
- const transformHandler = async (code, id, _options) => {
140
- if (!babel) return null;
141
- const { optimize, importMode } = config.build;
142
- if (!optimize && mode !== "build") return null;
143
- const { dictionariesDir, dynamicDictionariesDir, unmergedDictionariesDir, fetchDictionariesDir, mainDir } = config.system;
144
- /**
145
- * Handle Svelte compiled modules
146
- * Svelte plugin transforms .svelte files into JS
147
- * We need to transform the resulting JS code
148
- */
149
- const filename = id.split("?", 1)[0];
150
- const isSvelteFile = filename.endsWith(".svelte");
151
- if (!filesList.includes(filename)) {
152
- if (!isSvelteFile) return null;
153
- if (!filesList.some((f) => f === filename || f.startsWith(filename))) return null;
154
- }
155
- const dictionariesEntryPath = (0, node_path.join)(mainDir, "dictionaries.mjs");
156
- const unmergedDictionariesEntryPath = (0, node_path.join)(mainDir, "unmerged_dictionaries.mjs");
157
- const dynamicDictionariesEntryPath = (0, node_path.join)(mainDir, "dynamic_dictionaries.mjs");
158
- try {
159
- const result = babel.transformSync(code, {
160
- filename,
161
- plugins: [[_intlayer_babel.intlayerOptimizeBabelPlugin, {
162
- dictionariesDir,
163
- dictionariesEntryPath,
164
- unmergedDictionariesEntryPath,
165
- unmergedDictionariesDir,
166
- dynamicDictionariesDir,
167
- dynamicDictionariesEntryPath,
168
- fetchDictionariesDir,
169
- importMode,
170
- filesList,
171
- replaceDictionaryEntry: true,
172
- dictionaryModeMap
173
- }]],
174
- parserOpts: {
175
- sourceType: "module",
176
- allowImportExportEverywhere: true,
177
- plugins: [
178
- "typescript",
179
- "jsx",
180
- "decorators-legacy",
181
- "classProperties",
182
- "objectRestSpread",
183
- "asyncGenerators",
184
- "functionBind",
185
- "exportDefaultFrom",
186
- "exportNamespaceFrom",
187
- "dynamicImport",
188
- "nullishCoalescingOperator",
189
- "optionalChaining"
190
- ]
191
- }
192
- });
193
- if (result?.code) return {
194
- code: result.code,
195
- map: result.map
196
- };
197
- } catch (error) {
198
- logger(`Failed to transform Svelte file ${(0, node_path.relative)(projectRoot, filename)}: ${error}`, { level: "error" });
199
- }
200
- return null;
201
- };
202
- /**
203
- * Apply hook for determining when plugin should be active
204
- */
205
- const apply = (_config, env) => {
206
- const { optimize } = config?.build ?? {};
207
- const isEnabled = customCompilerConfig?.enabled ?? true;
208
- const isBuild = env.command === "build";
209
- return isEnabled && (isBuild ? optimize ?? true : optimize ?? false);
210
- };
211
- return {
212
- name: pluginName,
213
- enforce: "post",
214
- configResolved,
215
- buildStart,
216
- configureServer,
217
- handleHotUpdate,
218
- transform: {
219
- order: "post",
220
- handler: transformHandler
221
- },
222
- apply: (_viteConfig, env) => {
223
- if (!config) config = (0, _intlayer_config.getConfiguration)(configOptions);
224
- return apply(_viteConfig, env);
225
- }
226
- };
227
- };
228
- /**
229
- * Factory function for creating a Vite plugin
230
- */
231
- const svelteIntlayerCompiler = (options) => {
232
- return createSvelteIntlayerCompiler(options);
233
- };
234
- const SvelteIntlayerCompiler = createSvelteIntlayerCompiler;
235
-
236
- //#endregion
237
- exports.SvelteIntlayerCompiler = SvelteIntlayerCompiler;
238
- exports.createSvelteIntlayerCompiler = createSvelteIntlayerCompiler;
239
- exports.svelteIntlayerCompiler = svelteIntlayerCompiler;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`node:module`),t=require(`node:path`),n=require(`@intlayer/babel`),r=require(`@intlayer/chokidar/build`),i=require(`@intlayer/chokidar/utils`),a=require(`@intlayer/chokidar/watcher`),o=require(`@intlayer/config/logger`),s=require(`@intlayer/config/node`);const c=c=>{let l,u,d=``,f=`dev`,p=-1,m=[],h=null,g={},_=c?.configOptions,v=c?.compilerConfig,y=async()=>{let{traversePattern:e}=l.build,{baseDir:n,fileExtensions:r,codeDir:a}=l.content,{mainDir:o}=l.system,s=Array.from(new Set([n,...a])).flatMap(t=>(0,i.buildFilesList)({transformPattern:v?.transformPattern??e,excludePattern:[...v?.excludePattern??[],`**/node_modules/**`,...r.map(e=>`**/*${e}`)],baseDir:t})),c=(0,t.join)(o,`dictionaries.mjs`),u=(0,t.join)(o,`unmerged_dictionaries.mjs`);m=[...new Set([...s,c,u])]},b=async()=>{try{let{getDictionaries:e}=await import(`@intlayer/dictionaries-entry`),t=e();Object.values(t).forEach(e=>{g[e.key]=e.importMode??l.build.importMode})}catch{}},x=async t=>{f=t,l=(0,s.getConfiguration)(_),u=(0,o.getAppLogger)(l);try{h=(0,e.createRequire)(require(`url`).pathToFileURL(__filename).href)(`@babel/core`)}catch{u(`Failed to load @babel/core. Transformation will be disabled.`,{level:`warn`})}await y(),await b()},S=async e=>{let t=e.env?.DEV?`dev`:`build`;d=e.root,await x(t)},C=async()=>{let e=f===`build`;await(0,r.prepareIntlayer)(l,{clean:e,cacheTimeoutMs:e?1e3*30:1e3*60*60})},w=async()=>{l.content.watch&&(0,a.watch)({configuration:l})},T=async e=>{let{file:t,server:n}=e;if(!l.content.watchedFilesPatternWithPath.some(e=>new RegExp(e.replace(/\*\*/g,`.*`).replace(/\*/g,`[^/]*`)).test(t))){let e=l.system.dictionariesDir;if(t.startsWith(e))return[];p++;return}if(!(performance.now()-0<1e3))return n.ws.send({type:`full-reload`}),[]},E=async(e,r,i)=>{if(!h)return null;let{optimize:a,importMode:o}=l.build;if(!a&&f!==`build`)return null;let{dictionariesDir:s,dynamicDictionariesDir:c,unmergedDictionariesDir:p,fetchDictionariesDir:_,mainDir:v}=l.system,y=r.split(`?`,1)[0],b=y.endsWith(`.svelte`);if(!m.includes(y)&&(!b||!m.some(e=>e===y||e.startsWith(y))))return null;let x=(0,t.join)(v,`dictionaries.mjs`),S=(0,t.join)(v,`unmerged_dictionaries.mjs`),C=(0,t.join)(v,`dynamic_dictionaries.mjs`);try{let t=h.transformSync(e,{filename:y,plugins:[[n.intlayerOptimizeBabelPlugin,{dictionariesDir:s,dictionariesEntryPath:x,unmergedDictionariesEntryPath:S,unmergedDictionariesDir:p,dynamicDictionariesDir:c,dynamicDictionariesEntryPath:C,fetchDictionariesDir:_,importMode:o,filesList:m,replaceDictionaryEntry:!0,dictionaryModeMap:g}]],parserOpts:{sourceType:`module`,allowImportExportEverywhere:!0,plugins:[`typescript`,`jsx`,`decorators-legacy`,`classProperties`,`objectRestSpread`,`asyncGenerators`,`functionBind`,`exportDefaultFrom`,`exportNamespaceFrom`,`dynamicImport`,`nullishCoalescingOperator`,`optionalChaining`]}});if(t?.code)return{code:t.code,map:t.map}}catch(e){u(`Failed to transform Svelte file ${(0,t.relative)(d,y)}: ${e}`,{level:`error`})}return null},D=(e,t)=>{let{optimize:n}=l?.build??{},r=v?.enabled??!0,i=t.command===`build`;return r&&(i?n??!0:n??!1)};return{name:`svelte-intlayer-compiler`,enforce:`post`,configResolved:S,buildStart:C,configureServer:w,handleHotUpdate:T,transform:{order:`post`,handler:E},apply:(e,t)=>(l||=(0,s.getConfiguration)(_),D(e,t))}},l=e=>c(e),u=c;exports.SvelteIntlayerCompiler=u,exports.createSvelteIntlayerCompiler=c,exports.svelteIntlayerCompiler=l;
240
2
  //# sourceMappingURL=SvelteIntlayerCompiler.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"SvelteIntlayerCompiler.cjs","names":["intlayerOptimizeBabelPlugin"],"sources":["../../src/SvelteIntlayerCompiler.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join, relative } from 'node:path';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport {\n buildFilesList,\n watch as chokidarWatch,\n prepareIntlayer,\n} from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type {\n CompilerConfig,\n Dictionary,\n IntlayerConfig,\n} from '@intlayer/types';\n\n/**\n * Mode of the compiler\n */\nexport type CompilerMode = 'dev' | 'build';\n\n/**\n * Context for hot update handling\n */\nexport type HotUpdateContext = {\n file: string;\n server: {\n ws: { send: (message: { type: string }) => void };\n moduleGraph: {\n getModulesByFile: (file: string) => Set<unknown> | null | undefined;\n invalidateModule: (\n module: unknown,\n seen: Set<unknown>,\n timestamp: number,\n isHmr: boolean\n ) => void;\n };\n };\n timestamp: number;\n};\n\n/**\n * Transform result from the compiler\n */\nexport type TransformResult = {\n code?: string;\n map?: unknown;\n} | null;\n\n/**\n * Options for initializing the Svelte compiler\n */\nexport type SvelteIntlayerCompilerOptions = {\n /**\n * Configuration options for getting the intlayer configuration\n */\n configOptions?: GetConfigurationOptions;\n\n /**\n * Custom compiler configuration to override defaults\n */\n compilerConfig?: Partial<CompilerConfig>;\n};\n\n/**\n * Vite plugin object returned by the compiler\n */\nexport type SvelteIntlayerVitePlugin = {\n name: string;\n enforce: 'pre' | 'post';\n configResolved: (config: {\n env?: { DEV?: boolean };\n root: string;\n }) => Promise<void>;\n buildStart: () => Promise<void>;\n configureServer: () => Promise<void>;\n handleHotUpdate: (ctx: HotUpdateContext) => Promise<unknown[] | undefined>;\n transform: {\n order: 'pre' | 'post';\n handler: (\n code: string,\n id: string,\n options?: { ssr?: boolean }\n ) => Promise<TransformResult>;\n };\n apply: (config: unknown, env: { command: string }) => boolean;\n};\n\n/**\n * Create a SvelteIntlayerCompiler - A Vite-compatible compiler plugin for Svelte with Intlayer\n *\n * Handles Svelte components with special handling for:\n * - Script blocks in .svelte files\n * - TypeScript in Svelte files\n * - Svelte-specific transformations\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { svelte } from '@sveltejs/vite-plugin-svelte';\n * import { svelteIntlayerCompiler } from '@intlayer/svelte-compiler';\n *\n * export default defineConfig({\n * plugins: [svelte(), svelteIntlayerCompiler()],\n * });\n * ```\n */\nexport const createSvelteIntlayerCompiler = (\n options?: SvelteIntlayerCompilerOptions\n): SvelteIntlayerVitePlugin => {\n const pluginName = 'svelte-intlayer-compiler';\n\n // Private state\n let config: IntlayerConfig;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let mode: CompilerMode = 'dev';\n let hmrVersion = -1;\n const lastSourceTriggeredWrite = 0;\n let filesList: string[] = [];\n\n // @ts-expect-error - @babel/core is a peer dependency\n let babel: typeof import('@babel/core') | null = null;\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n const configOptions = options?.configOptions;\n const customCompilerConfig = options?.compilerConfig;\n\n /**\n * Build the list of files to transform based on configuration patterns\n * Includes Svelte-specific patterns\n */\n const buildFilesListFn = async (): Promise<void> => {\n const { traversePattern } = config.build;\n const { baseDir, fileExtensions, codeDir } = config.content;\n const { mainDir } = config.system;\n\n const distinctRoots = Array.from(new Set([baseDir, ...codeDir]));\n\n const filesListPattern = distinctRoots.flatMap((root) =>\n buildFilesList({\n transformPattern:\n customCompilerConfig?.transformPattern ?? traversePattern,\n excludePattern: [\n ...(customCompilerConfig?.excludePattern ?? []),\n '**/node_modules/**',\n ...fileExtensions.map((pattern) => `**/*${pattern}`),\n ],\n baseDir: root,\n })\n );\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n filesList = [\n ...new Set([\n ...filesListPattern,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ]),\n ];\n };\n\n /**\n * Load dictionary keys that have specific import modes\n */\n const loadDictionaryModeMap = async (): Promise<void> => {\n try {\n const { getDictionaries } = await import('@intlayer/dictionaries-entry');\n const dictionaries = getDictionaries() as Record<string, Dictionary>;\n\n Object.values(dictionaries).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? config.build.importMode;\n });\n } catch {\n // ignore\n }\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n mode = compilerMode;\n config = getConfiguration(configOptions);\n logger = getAppLogger(config);\n\n // Load Babel dynamically\n try {\n const localRequire = createRequire(import.meta.url);\n babel = localRequire('@babel/core');\n } catch {\n logger('Failed to load @babel/core. Transformation will be disabled.', {\n level: 'warn',\n });\n }\n\n // Build files list for transformation\n await buildFilesListFn();\n\n // Load dictionary mode map\n await loadDictionaryModeMap();\n };\n\n /**\n * Vite hook: configResolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n }): Promise<void> => {\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n await init(compilerMode);\n };\n\n /**\n * Prepare intlayer dictionaries and types\n */\n const buildStart = async (): Promise<void> => {\n const isBuild = mode === 'build';\n\n await prepareIntlayer(config, {\n clean: isBuild,\n cacheTimeoutMs: isBuild ? 1000 * 30 : 1000 * 60 * 60,\n });\n };\n\n /**\n * Configure the dev server with file watching\n */\n const configureServer = async (): Promise<void> => {\n if (config.content.watch) {\n chokidarWatch({ configuration: config });\n }\n };\n\n /**\n * Handle HMR for content changes\n */\n const handleHotUpdate = async (\n ctx: HotUpdateContext\n ): Promise<unknown[] | undefined> => {\n const { file, server } = ctx;\n\n // Check if this is a content declaration file\n const isContentFile = config.content.watchedFilesPatternWithPath.some(\n (pattern: string) => {\n const regex = new RegExp(\n pattern.replace(/\\*\\*/g, '.*').replace(/\\*/g, '[^/]*')\n );\n return regex.test(file);\n }\n );\n\n if (!isContentFile) {\n const dictionariesDir = config.system.dictionariesDir;\n if (file.startsWith(dictionariesDir)) {\n return [];\n }\n hmrVersion++;\n return undefined;\n }\n\n const sourceTriggered = performance.now() - lastSourceTriggeredWrite < 1000;\n\n if (!sourceTriggered) {\n server.ws.send({ type: 'full-reload' });\n return [];\n }\n\n return undefined;\n };\n\n /**\n * Transform handler with Svelte-specific handling\n */\n const transformHandler = async (\n code: string,\n id: string,\n _options?: { ssr?: boolean }\n ): Promise<TransformResult> => {\n if (!babel) {\n return null;\n }\n\n const { optimize, importMode } = config.build;\n\n if (!optimize && mode !== 'build') {\n return null;\n }\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = config.system;\n\n /**\n * Handle Svelte compiled modules\n * Svelte plugin transforms .svelte files into JS\n * We need to transform the resulting JS code\n */\n const filename = id.split('?', 1)[0];\n\n // Check if this file should be transformed\n const isSvelteFile = filename.endsWith('.svelte');\n\n if (!filesList.includes(filename)) {\n // Also check if it's a compiled Svelte file\n if (!isSvelteFile) {\n return null;\n }\n // Check if the base svelte file is in our list\n if (!filesList.some((f) => f === filename || f.startsWith(filename))) {\n return null;\n }\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n try {\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n } catch (error) {\n logger(\n `Failed to transform Svelte file ${relative(projectRoot, filename)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n return null;\n };\n\n /**\n * Apply hook for determining when plugin should be active\n */\n const apply = (_config: unknown, env: { command: string }): boolean => {\n const { optimize } = config?.build ?? {};\n const isEnabled = customCompilerConfig?.enabled ?? true;\n const isBuild = env.command === 'build';\n\n return isEnabled && (isBuild ? (optimize ?? true) : (optimize ?? false));\n };\n\n return {\n name: pluginName,\n enforce: 'post', // Run after Svelte plugin\n configResolved,\n buildStart,\n configureServer,\n handleHotUpdate,\n transform: {\n order: 'post', // Run after Svelte plugin transformation\n handler: transformHandler,\n },\n apply: (_viteConfig: unknown, env: { command: string }) => {\n if (!config) {\n config = getConfiguration(configOptions);\n }\n return apply(_viteConfig, env);\n },\n };\n};\n\n/**\n * Factory function for creating a Vite plugin\n */\nexport const svelteIntlayerCompiler = (\n options?: SvelteIntlayerCompilerOptions\n): SvelteIntlayerVitePlugin => {\n return createSvelteIntlayerCompiler(options);\n};\n\n// Legacy export for backwards compatibility\nexport const SvelteIntlayerCompiler = createSvelteIntlayerCompiler;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAa,gCACX,YAC6B;CAC7B,MAAM,aAAa;CAGnB,IAAI;CACJ,IAAI;CACJ,IAAI,cAAc;CAClB,IAAI,OAAqB;CACzB,IAAI,aAAa;CACjB,MAAM,2BAA2B;CACjC,IAAI,YAAsB,EAAE;CAG5B,IAAI,QAA6C;CACjD,MAAM,oBAAoE,EAAE;CAE5E,MAAM,gBAAgB,SAAS;CAC/B,MAAM,uBAAuB,SAAS;;;;;CAMtC,MAAM,mBAAmB,YAA2B;EAClD,MAAM,EAAE,oBAAoB,OAAO;EACnC,MAAM,EAAE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AC7B,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACD;KACF;IACF,CAAC;AAEF,OAAI,QAAQ,KACV,QAAO;IACL,MAAM,OAAO;IACb,KAAK,OAAO;IACb;WAEI,OAAO;AACd,UACE,2DAA4C,aAAa,SAAS,CAAC,IAAI,SACvE,EACE,OAAO,SACR,CACF;;AAGH,SAAO;;;;;CAMT,MAAM,SAAS,SAAkB,QAAsC;EACrE,MAAM,EAAE,aAAa,QAAQ,SAAS,EAAE;EACxC,MAAM,YAAY,sBAAsB,WAAW;EACnD,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAO,cAAc,UAAW,YAAY,OAAS,YAAY;;AAGnE,QAAO;EACL,MAAM;EACN,SAAS;EACT;EACA;EACA;EACA;EACA,WAAW;GACT,OAAO;GACP,SAAS;GACV;EACD,QAAQ,aAAsB,QAA6B;AACzD,OAAI,CAAC,OACH,iDAA0B,cAAc;AAE1C,UAAO,MAAM,aAAa,IAAI;;EAEjC;;;;;AAMH,MAAa,0BACX,YAC6B;AAC7B,QAAO,6BAA6B,QAAQ;;AAI9C,MAAa,yBAAyB"}
1
+ {"version":3,"file":"SvelteIntlayerCompiler.cjs","names":["intlayerOptimizeBabelPlugin"],"sources":["../../src/SvelteIntlayerCompiler.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join, relative } from 'node:path';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { buildFilesList } from '@intlayer/chokidar/utils';\nimport { watch as chokidarWatch } from '@intlayer/chokidar/watcher';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type {\n CompilerConfig,\n Dictionary,\n IntlayerConfig,\n} from '@intlayer/types';\n\n/**\n * Mode of the compiler\n */\nexport type CompilerMode = 'dev' | 'build';\n\n/**\n * Context for hot update handling\n */\nexport type HotUpdateContext = {\n file: string;\n server: {\n ws: { send: (message: { type: string }) => void };\n moduleGraph: {\n getModulesByFile: (file: string) => Set<unknown> | null | undefined;\n invalidateModule: (\n module: unknown,\n seen: Set<unknown>,\n timestamp: number,\n isHmr: boolean\n ) => void;\n };\n };\n timestamp: number;\n};\n\n/**\n * Transform result from the compiler\n */\nexport type TransformResult = {\n code?: string;\n map?: unknown;\n} | null;\n\n/**\n * Options for initializing the Svelte compiler\n */\nexport type SvelteIntlayerCompilerOptions = {\n /**\n * Configuration options for getting the intlayer configuration\n */\n configOptions?: GetConfigurationOptions;\n\n /**\n * Custom compiler configuration to override defaults\n */\n compilerConfig?: Partial<CompilerConfig>;\n};\n\n/**\n * Vite plugin object returned by the compiler\n */\nexport type SvelteIntlayerVitePlugin = {\n name: string;\n enforce: 'pre' | 'post';\n configResolved: (config: {\n env?: { DEV?: boolean };\n root: string;\n }) => Promise<void>;\n buildStart: () => Promise<void>;\n configureServer: () => Promise<void>;\n handleHotUpdate: (ctx: HotUpdateContext) => Promise<unknown[] | undefined>;\n transform: {\n order: 'pre' | 'post';\n handler: (\n code: string,\n id: string,\n options?: { ssr?: boolean }\n ) => Promise<TransformResult>;\n };\n apply: (config: unknown, env: { command: string }) => boolean;\n};\n\n/**\n * Create a SvelteIntlayerCompiler - A Vite-compatible compiler plugin for Svelte with Intlayer\n *\n * Handles Svelte components with special handling for:\n * - Script blocks in .svelte files\n * - TypeScript in Svelte files\n * - Svelte-specific transformations\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { svelte } from '@sveltejs/vite-plugin-svelte';\n * import { svelteIntlayerCompiler } from '@intlayer/svelte-compiler';\n *\n * export default defineConfig({\n * plugins: [svelte(), svelteIntlayerCompiler()],\n * });\n * ```\n */\nexport const createSvelteIntlayerCompiler = (\n options?: SvelteIntlayerCompilerOptions\n): SvelteIntlayerVitePlugin => {\n const pluginName = 'svelte-intlayer-compiler';\n\n // Private state\n let config: IntlayerConfig;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let mode: CompilerMode = 'dev';\n let hmrVersion = -1;\n const lastSourceTriggeredWrite = 0;\n let filesList: string[] = [];\n\n // @ts-expect-error - @babel/core is a peer dependency\n let babel: typeof import('@babel/core') | null = null;\n const dictionaryModeMap: Record<string, 'static' | 'dynamic' | 'fetch'> = {};\n\n const configOptions = options?.configOptions;\n const customCompilerConfig = options?.compilerConfig;\n\n /**\n * Build the list of files to transform based on configuration patterns\n * Includes Svelte-specific patterns\n */\n const buildFilesListFn = async (): Promise<void> => {\n const { traversePattern } = config.build;\n const { baseDir, fileExtensions, codeDir } = config.content;\n const { mainDir } = config.system;\n\n const distinctRoots = Array.from(new Set([baseDir, ...codeDir]));\n\n const filesListPattern = distinctRoots.flatMap((root) =>\n buildFilesList({\n transformPattern:\n customCompilerConfig?.transformPattern ?? traversePattern,\n excludePattern: [\n ...(customCompilerConfig?.excludePattern ?? []),\n '**/node_modules/**',\n ...fileExtensions.map((pattern) => `**/*${pattern}`),\n ],\n baseDir: root,\n })\n );\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n filesList = [\n ...new Set([\n ...filesListPattern,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ]),\n ];\n };\n\n /**\n * Load dictionary keys that have specific import modes\n */\n const loadDictionaryModeMap = async (): Promise<void> => {\n try {\n const { getDictionaries } = await import('@intlayer/dictionaries-entry');\n const dictionaries = getDictionaries() as Record<string, Dictionary>;\n\n Object.values(dictionaries).forEach((dictionary) => {\n dictionaryModeMap[dictionary.key] =\n dictionary.importMode ?? config.build.importMode;\n });\n } catch {\n // ignore\n }\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n mode = compilerMode;\n config = getConfiguration(configOptions);\n logger = getAppLogger(config);\n\n // Load Babel dynamically\n try {\n const localRequire = createRequire(import.meta.url);\n babel = localRequire('@babel/core');\n } catch {\n logger('Failed to load @babel/core. Transformation will be disabled.', {\n level: 'warn',\n });\n }\n\n // Build files list for transformation\n await buildFilesListFn();\n\n // Load dictionary mode map\n await loadDictionaryModeMap();\n };\n\n /**\n * Vite hook: configResolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n }): Promise<void> => {\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n await init(compilerMode);\n };\n\n /**\n * Prepare intlayer dictionaries and types\n */\n const buildStart = async (): Promise<void> => {\n const isBuild = mode === 'build';\n\n await prepareIntlayer(config, {\n clean: isBuild,\n cacheTimeoutMs: isBuild ? 1000 * 30 : 1000 * 60 * 60,\n });\n };\n\n /**\n * Configure the dev server with file watching\n */\n const configureServer = async (): Promise<void> => {\n if (config.content.watch) {\n chokidarWatch({ configuration: config });\n }\n };\n\n /**\n * Handle HMR for content changes\n */\n const handleHotUpdate = async (\n ctx: HotUpdateContext\n ): Promise<unknown[] | undefined> => {\n const { file, server } = ctx;\n\n // Check if this is a content declaration file\n const isContentFile = config.content.watchedFilesPatternWithPath.some(\n (pattern: string) => {\n const regex = new RegExp(\n pattern.replace(/\\*\\*/g, '.*').replace(/\\*/g, '[^/]*')\n );\n return regex.test(file);\n }\n );\n\n if (!isContentFile) {\n const dictionariesDir = config.system.dictionariesDir;\n if (file.startsWith(dictionariesDir)) {\n return [];\n }\n hmrVersion++;\n return undefined;\n }\n\n const sourceTriggered = performance.now() - lastSourceTriggeredWrite < 1000;\n\n if (!sourceTriggered) {\n server.ws.send({ type: 'full-reload' });\n return [];\n }\n\n return undefined;\n };\n\n /**\n * Transform handler with Svelte-specific handling\n */\n const transformHandler = async (\n code: string,\n id: string,\n _options?: { ssr?: boolean }\n ): Promise<TransformResult> => {\n if (!babel) {\n return null;\n }\n\n const { optimize, importMode } = config.build;\n\n if (!optimize && mode !== 'build') {\n return null;\n }\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = config.system;\n\n /**\n * Handle Svelte compiled modules\n * Svelte plugin transforms .svelte files into JS\n * We need to transform the resulting JS code\n */\n const filename = id.split('?', 1)[0];\n\n // Check if this file should be transformed\n const isSvelteFile = filename.endsWith('.svelte');\n\n if (!filesList.includes(filename)) {\n // Also check if it's a compiled Svelte file\n if (!isSvelteFile) {\n return null;\n }\n // Check if the base svelte file is in our list\n if (!filesList.some((f) => f === filename || f.startsWith(filename))) {\n return null;\n }\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n try {\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n dictionaryModeMap,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n } catch (error) {\n logger(\n `Failed to transform Svelte file ${relative(projectRoot, filename)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n return null;\n };\n\n /**\n * Apply hook for determining when plugin should be active\n */\n const apply = (_config: unknown, env: { command: string }): boolean => {\n const { optimize } = config?.build ?? {};\n const isEnabled = customCompilerConfig?.enabled ?? true;\n const isBuild = env.command === 'build';\n\n return isEnabled && (isBuild ? (optimize ?? true) : (optimize ?? false));\n };\n\n return {\n name: pluginName,\n enforce: 'post', // Run after Svelte plugin\n configResolved,\n buildStart,\n configureServer,\n handleHotUpdate,\n transform: {\n order: 'post', // Run after Svelte plugin transformation\n handler: transformHandler,\n },\n apply: (_viteConfig: unknown, env: { command: string }) => {\n if (!config) {\n config = getConfiguration(configOptions);\n }\n return apply(_viteConfig, env);\n },\n };\n};\n\n/**\n * Factory function for creating a Vite plugin\n */\nexport const svelteIntlayerCompiler = (\n options?: SvelteIntlayerCompilerOptions\n): SvelteIntlayerVitePlugin => {\n return createSvelteIntlayerCompiler(options);\n};\n\n// Legacy export for backwards compatibility\nexport const SvelteIntlayerCompiler = createSvelteIntlayerCompiler;\n"],"mappings":"gVA6GA,MAAa,EACX,GAC6B,CAC7B,IAGI,EACA,EACA,EAAc,GACd,EAAqB,MACrB,EAAa,GAEb,EAAsB,EAAE,CAGxB,EAA6C,KAC3C,EAAoE,EAAE,CAEtE,EAAgB,GAAS,cACzB,EAAuB,GAAS,eAMhC,EAAmB,SAA2B,CAClD,GAAM,CAAE,mBAAoB,EAAO,MAC7B,CAAE,UAAS,iBAAgB,WAAY,EAAO,QAC9C,CAAE,WAAY,EAAO,OAIrB,EAFgB,MAAM,KAAK,IAAI,IAAI,CAAC,EAAS,GAAG,EAAQ,CAAC,CAAC,CAEzB,QAAS,IAAA,EAAA,EAAA,gBAC/B,CACb,iBACE,GAAsB,kBAAoB,EAC5C,eAAgB,CACd,GAAI,GAAsB,gBAAkB,EAAE,CAC9C,qBACA,GAAG,EAAe,IAAK,GAAY,OAAO,IAAU,CACrD,CACD,QAAS,EACV,CAAC,CACH,CAEK,GAAA,EAAA,EAAA,MAA6B,EAAS,mBAAmB,CACzD,GAAA,EAAA,EAAA,MACJ,EACA,4BACD,CAED,EAAY,CACV,GAAG,IAAI,IAAI,CACT,GAAG,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,GAAS,GAAY,KAGnE,MAAO,CACL,KAAM,2BACN,QAAS,OACT,iBACA,aACA,kBACA,kBACA,UAAW,CACT,MAAO,OACP,QAAS,EACV,CACD,OAAQ,EAAsB,KAC5B,AACE,KAAA,EAAA,EAAA,kBAA0B,EAAc,CAEnC,EAAM,EAAa,EAAI,EAEjC,EAMU,EACX,GAEO,EAA6B,EAAQ,CAIjC,EAAyB"}
@@ -1,13 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_SvelteIntlayerCompiler = require('./SvelteIntlayerCompiler.cjs');
3
- const require_svelte_intlayer_extract = require('./svelte-intlayer-extract.cjs');
4
-
5
- exports.ATTRIBUTES_TO_EXTRACT = require_svelte_intlayer_extract.ATTRIBUTES_TO_EXTRACT;
6
- exports.SvelteIntlayerCompiler = require_SvelteIntlayerCompiler.SvelteIntlayerCompiler;
7
- exports.createSvelteIntlayerCompiler = require_SvelteIntlayerCompiler.createSvelteIntlayerCompiler;
8
- exports.defaultShouldExtract = require_svelte_intlayer_extract.defaultShouldExtract;
9
- exports.extractDictionaryKeyFromPath = require_svelte_intlayer_extract.extractDictionaryKeyFromPath;
10
- exports.generateKey = require_svelte_intlayer_extract.generateKey;
11
- exports.intlayerSvelteExtract = require_svelte_intlayer_extract.intlayerSvelteExtract;
12
- exports.shouldProcessFile = require_svelte_intlayer_extract.shouldProcessFile;
13
- exports.svelteIntlayerCompiler = require_SvelteIntlayerCompiler.svelteIntlayerCompiler;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./SvelteIntlayerCompiler.cjs`),t=require(`./svelte-intlayer-extract.cjs`);exports.ATTRIBUTES_TO_EXTRACT=t.ATTRIBUTES_TO_EXTRACT,exports.SvelteIntlayerCompiler=e.SvelteIntlayerCompiler,exports.createSvelteIntlayerCompiler=e.createSvelteIntlayerCompiler,exports.defaultShouldExtract=t.defaultShouldExtract,exports.extractDictionaryKeyFromPath=t.extractDictionaryKeyFromPath,exports.generateKey=t.generateKey,exports.intlayerSvelteExtract=t.intlayerSvelteExtract,exports.shouldProcessFile=t.shouldProcessFile,exports.svelteIntlayerCompiler=e.svelteIntlayerCompiler;
@@ -1,244 +1,3 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- let node_path = require("node:path");
3
- let _babel_core = require("@babel/core");
4
-
5
- //#region src/svelte-intlayer-extract.ts
6
- /**
7
- * Attributes that should be extracted for localization
8
- */
9
- const ATTRIBUTES_TO_EXTRACT = [
10
- "title",
11
- "placeholder",
12
- "alt",
13
- "aria-label",
14
- "label"
15
- ];
16
- /**
17
- * Default function to determine if a string should be extracted
18
- */
19
- const defaultShouldExtract = (text) => {
20
- const trimmed = text.trim();
21
- if (!trimmed) return false;
22
- if (!trimmed.includes(" ")) return false;
23
- if (!/^[A-Z]/.test(trimmed)) return false;
24
- if (trimmed.startsWith("{") || trimmed.startsWith("v-")) return false;
25
- return true;
26
- };
27
- /**
28
- * Generate a unique key from text
29
- */
30
- const generateKey = (text, existingKeys) => {
31
- let key = text.replace(/\s+/g, " ").replace(/_+/g, " ").replace(/-+/g, " ").replace(/[^a-zA-Z0-9 ]/g, "").trim().split(" ").filter(Boolean).slice(0, 5).map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
32
- if (!key) key = "content";
33
- if (existingKeys.has(key)) {
34
- let i = 1;
35
- while (existingKeys.has(`${key}${i}`)) i++;
36
- key = `${key}${i}`;
37
- }
38
- return key;
39
- };
40
- /**
41
- * Extract dictionary key from file path
42
- */
43
- const extractDictionaryKeyFromPath = (filePath) => {
44
- let baseName = (0, node_path.basename)(filePath, (0, node_path.extname)(filePath));
45
- if (baseName === "index") baseName = (0, node_path.basename)((0, node_path.dirname)(filePath));
46
- return `comp-${baseName.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase()}`;
47
- };
48
- /**
49
- * Check if a file should be processed based on filesList
50
- */
51
- const shouldProcessFile = (filename, filesList) => {
52
- if (!filename) return false;
53
- if (!filesList || filesList.length === 0) return true;
54
- const normalizedFilename = filename.replace(/\\/g, "/");
55
- return filesList.some((f) => {
56
- return f.replace(/\\/g, "/") === normalizedFilename;
57
- });
58
- };
59
- /**
60
- * Svelte extraction plugin that extracts content and transforms Svelte components to use useIntlayer.
61
- *
62
- * This plugin:
63
- * 1. Scans Svelte files for extractable text (template text, attributes)
64
- * 2. Auto-injects useIntlayer import and store binding
65
- * 3. Reports extracted content via onExtract callback (for the compiler to write dictionaries)
66
- * 4. Replaces extractable strings with content references using Svelte's reactive `$` prefix
67
- *
68
- * ## Input
69
- * ```svelte
70
- * <h1>Hello World</h1>
71
- * <p>Welcome to our app</p>
72
- * ```
73
- *
74
- * ## Output
75
- * ```svelte
76
- * <script>
77
- * import { useIntlayer } from 'svelte-intlayer';
78
- * const content = useIntlayer('hello-world');
79
- * <\/script>
80
- * <h1>{$content.helloWorld}</h1>
81
- * <p>{$content.welcomeToOurApp}</p>
82
- * ```
83
- *
84
- * Note: Svelte uses reactive stores with `$` prefix for automatic subscription.
85
- * The `useIntlayer` composable returns a Svelte store that can be accessed reactively.
86
- */
87
- const intlayerSvelteExtract = async (code, filename, options = {}) => {
88
- const { defaultLocale = "en", packageName = "svelte-intlayer", filesList, shouldExtract = defaultShouldExtract, onExtract } = options;
89
- if (!shouldProcessFile(filename, filesList)) return null;
90
- if (!filename.endsWith(".svelte")) return null;
91
- let MagicString;
92
- try {
93
- MagicString = (await import("magic-string")).default;
94
- } catch {
95
- console.warn("Svelte extraction: magic-string not found. Install it to enable Svelte content extraction.");
96
- return null;
97
- }
98
- const magic = new MagicString(code);
99
- const extractedContent = {};
100
- const existingKeys = /* @__PURE__ */ new Set();
101
- const dictionaryKey = extractDictionaryKeyFromPath(filename);
102
- const replacements = [];
103
- const scriptBlockRegex = /<script[^>]*>[\s\S]*?<\/script>/gi;
104
- const styleBlockRegex = /<style[^>]*>[\s\S]*?<\/style>/gi;
105
- const skipRanges = [];
106
- const scriptMatches = code.matchAll(scriptBlockRegex);
107
- for (const match of scriptMatches) if (match.index !== void 0) skipRanges.push({
108
- start: match.index,
109
- end: match.index + match[0].length
110
- });
111
- const styleMatches = code.matchAll(styleBlockRegex);
112
- for (const match of styleMatches) if (match.index !== void 0) skipRanges.push({
113
- start: match.index,
114
- end: match.index + match[0].length
115
- });
116
- skipRanges.sort((a, b) => a.start - b.start);
117
- const isInSkipRange = (pos) => {
118
- return skipRanges.some((range) => pos >= range.start && pos < range.end);
119
- };
120
- const textMatches = code.matchAll(/>([^<]+)</g);
121
- for (const match of textMatches) {
122
- if (match.index === void 0) continue;
123
- const textStart = match.index + 1;
124
- const text = match[1];
125
- const textEnd = textStart + text.length;
126
- if (isInSkipRange(textStart)) continue;
127
- if (shouldExtract(text)) {
128
- const key = generateKey(text, existingKeys);
129
- existingKeys.add(key);
130
- const normalizedValue = text.replace(/\s+/g, " ").trim();
131
- replacements.push({
132
- start: textStart,
133
- end: textEnd,
134
- replacement: `{$content.${key}}`,
135
- key,
136
- value: normalizedValue
137
- });
138
- }
139
- }
140
- for (const attrName of ATTRIBUTES_TO_EXTRACT) {
141
- const attrRegex = new RegExp(`(${attrName})=["']([^"']+)["']`, "gi");
142
- const attrMatches = code.matchAll(attrRegex);
143
- for (const match of attrMatches) {
144
- if (match.index === void 0) continue;
145
- const attrStart = match.index;
146
- const attrEnd = attrStart + match[0].length;
147
- const text = match[2];
148
- if (isInSkipRange(attrStart)) continue;
149
- if (shouldExtract(text)) {
150
- const key = generateKey(text, existingKeys);
151
- existingKeys.add(key);
152
- replacements.push({
153
- start: attrStart,
154
- end: attrEnd,
155
- replacement: `${attrName}={$content.${key}.value}`,
156
- key,
157
- value: text.trim()
158
- });
159
- }
160
- }
161
- }
162
- replacements.sort((a, b) => b.start - a.start);
163
- for (const { start, end, replacement, key, value } of replacements) {
164
- magic.overwrite(start, end, replacement);
165
- extractedContent[key] = value;
166
- }
167
- const scriptMatch = /<script[^>]*>([\s\S]*?)<\/script>/.exec(code);
168
- let hasScriptExtraction = false;
169
- const scriptContent = scriptMatch ? scriptMatch[1] : "";
170
- if (scriptMatch) {
171
- const openTagEndIndex = scriptMatch[0].indexOf(">") + 1;
172
- const offset = scriptMatch.index + openTagEndIndex;
173
- try {
174
- (0, _babel_core.traverse)((0, _babel_core.parse)(scriptContent, { parserOpts: {
175
- sourceType: "module",
176
- plugins: ["typescript", "jsx"]
177
- } }), { StringLiteral(path) {
178
- if (path.parentPath.isImportDeclaration()) return;
179
- if (path.parentPath.isExportDeclaration()) return;
180
- if (path.parentPath.isImportSpecifier()) return;
181
- if (path.parentPath.isObjectProperty() && path.key === "key") return;
182
- if (path.parentPath.isCallExpression()) {
183
- const callee = path.parentPath.node.callee;
184
- if (_babel_core.types.isMemberExpression(callee) && _babel_core.types.isIdentifier(callee.object) && callee.object.name === "console") return;
185
- if (_babel_core.types.isIdentifier(callee) && (callee.name === "useIntlayer" || callee.name === "t")) return;
186
- if (callee.type === "Import") return;
187
- if (_babel_core.types.isIdentifier(callee) && callee.name === "require") return;
188
- }
189
- const text = path.node.value;
190
- if (shouldExtract(text)) {
191
- const key = generateKey(text, existingKeys);
192
- existingKeys.add(key);
193
- extractedContent[key] = text.trim();
194
- hasScriptExtraction = true;
195
- if (path.node.start != null && path.node.end != null) magic.overwrite(offset + path.node.start, offset + path.node.end, `get(content).${key}`);
196
- }
197
- } });
198
- } catch (e) {
199
- console.warn(`Svelte extraction: Failed to parse script content for ${filename}`, e);
200
- }
201
- }
202
- if (Object.keys(extractedContent).length === 0) return null;
203
- const hasUseIntlayerImport = /import\s*{[^}]*useIntlayer[^}]*}\s*from\s*['"][^'"]+['"]/.test(scriptContent) || /import\s+useIntlayer\s+from\s*['"][^'"]+['"]/.test(scriptContent);
204
- const hasGetImport = /import\s*{[^}]*get[^}]*}\s*from\s*['"]svelte\/store['"]/.test(scriptContent);
205
- const hasContentDeclaration = /const\s+content\s*=\s*useIntlayer\s*\(/.test(scriptContent);
206
- if (hasUseIntlayerImport && hasContentDeclaration) return null;
207
- const importStmt = hasUseIntlayerImport ? "" : `import { useIntlayer } from '${packageName}';`;
208
- const getImportStmt = hasScriptExtraction && !hasGetImport ? `import { get } from 'svelte/store';` : "";
209
- const contentDecl = hasContentDeclaration ? "" : `const content = useIntlayer('${dictionaryKey}');`;
210
- const injectionParts = [
211
- importStmt,
212
- getImportStmt,
213
- contentDecl
214
- ].filter(Boolean);
215
- if (injectionParts.length === 0) return null;
216
- const injection = `\n ${injectionParts.join("\n ")}\n`;
217
- if (scriptMatch) {
218
- const scriptContentStart = scriptMatch.index + scriptMatch[0].indexOf(">") + 1;
219
- magic.appendLeft(scriptContentStart, injection);
220
- } else magic.prepend(`<script>\n ${importStmt}\n ${hasScriptExtraction ? "import { get } from 'svelte/store';" : ""}\n ${contentDecl}\n<\/script>\n\n`);
221
- if (onExtract) onExtract({
222
- dictionaryKey,
223
- filePath: filename,
224
- content: { ...extractedContent },
225
- locale: defaultLocale
226
- });
227
- return {
228
- code: magic.toString(),
229
- map: magic.generateMap({
230
- source: filename,
231
- includeContent: true
232
- }),
233
- extracted: true
234
- };
235
- };
236
-
237
- //#endregion
238
- exports.ATTRIBUTES_TO_EXTRACT = ATTRIBUTES_TO_EXTRACT;
239
- exports.defaultShouldExtract = defaultShouldExtract;
240
- exports.extractDictionaryKeyFromPath = extractDictionaryKeyFromPath;
241
- exports.generateKey = generateKey;
242
- exports.intlayerSvelteExtract = intlayerSvelteExtract;
243
- exports.shouldProcessFile = shouldProcessFile;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`node:path`),t=require(`@babel/core`);const n=[`title`,`placeholder`,`alt`,`aria-label`,`label`],r=e=>{let t=e.trim();return!(!t||!t.includes(` `)||!/^[A-Z]/.test(t)||t.startsWith(`{`)||t.startsWith(`v-`))},i=(e,t)=>{let n=e.replace(/\s+/g,` `).replace(/_+/g,` `).replace(/-+/g,` `).replace(/[^a-zA-Z0-9 ]/g,``).trim().split(` `).filter(Boolean).slice(0,5).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``);if(n||=`content`,t.has(n)){let e=1;for(;t.has(`${n}${e}`);)e++;n=`${n}${e}`}return n},a=t=>{let n=(0,e.basename)(t,(0,e.extname)(t));return n===`index`&&(n=(0,e.basename)((0,e.dirname)(t))),`comp-${n.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}`},o=(e,t)=>{if(!e)return!1;if(!t||t.length===0)return!0;let n=e.replace(/\\/g,`/`);return t.some(e=>e.replace(/\\/g,`/`)===n)},s=async(e,s,c={})=>{let{defaultLocale:l=`en`,packageName:u=`svelte-intlayer`,filesList:d,shouldExtract:f=r,onExtract:p}=c;if(!o(s,d)||!s.endsWith(`.svelte`))return null;let m;try{m=(await import(`magic-string`)).default}catch{return console.warn(`Svelte extraction: magic-string not found. Install it to enable Svelte content extraction.`),null}let h=new m(e),g={},_=new Set,v=a(s),y=[],b=/<script[^>]*>[\s\S]*?<\/script>/gi,x=/<style[^>]*>[\s\S]*?<\/style>/gi,S=[],C=e.matchAll(b);for(let e of C)e.index!==void 0&&S.push({start:e.index,end:e.index+e[0].length});let w=e.matchAll(x);for(let e of w)e.index!==void 0&&S.push({start:e.index,end:e.index+e[0].length});S.sort((e,t)=>e.start-t.start);let T=e=>S.some(t=>e>=t.start&&e<t.end),E=e.matchAll(/>([^<]+)</g);for(let e of E){if(e.index===void 0)continue;let t=e.index+1,n=e[1],r=t+n.length;if(!T(t)&&f(n)){let e=i(n,_);_.add(e);let a=n.replace(/\s+/g,` `).trim();y.push({start:t,end:r,replacement:`{$content.${e}}`,key:e,value:a})}}for(let t of n){let n=RegExp(`(${t})=["']([^"']+)["']`,`gi`),r=e.matchAll(n);for(let e of r){if(e.index===void 0)continue;let n=e.index,r=n+e[0].length,a=e[2];if(!T(n)&&f(a)){let e=i(a,_);_.add(e),y.push({start:n,end:r,replacement:`${t}={$content.${e}.value}`,key:e,value:a.trim()})}}}y.sort((e,t)=>t.start-e.start);for(let{start:e,end:t,replacement:n,key:r,value:i}of y)h.overwrite(e,t,n),g[r]=i;let D=/<script[^>]*>([\s\S]*?)<\/script>/.exec(e),O=!1,k=D?D[1]:``;if(D){let e=D[0].indexOf(`>`)+1,n=D.index+e;try{(0,t.traverse)((0,t.parse)(k,{parserOpts:{sourceType:`module`,plugins:[`typescript`,`jsx`]}}),{StringLiteral(e){if(e.parentPath.isImportDeclaration()||e.parentPath.isExportDeclaration()||e.parentPath.isImportSpecifier()||e.parentPath.isObjectProperty()&&e.key===`key`)return;if(e.parentPath.isCallExpression()){let n=e.parentPath.node.callee;if(t.types.isMemberExpression(n)&&t.types.isIdentifier(n.object)&&n.object.name===`console`||t.types.isIdentifier(n)&&(n.name===`useIntlayer`||n.name===`t`)||n.type===`Import`||t.types.isIdentifier(n)&&n.name===`require`)return}let r=e.node.value;if(f(r)){let t=i(r,_);_.add(t),g[t]=r.trim(),O=!0,e.node.start!=null&&e.node.end!=null&&h.overwrite(n+e.node.start,n+e.node.end,`get(content).${t}`)}}})}catch(e){console.warn(`Svelte extraction: Failed to parse script content for ${s}`,e)}}if(Object.keys(g).length===0)return null;let A=/import\s*{[^}]*useIntlayer[^}]*}\s*from\s*['"][^'"]+['"]/.test(k)||/import\s+useIntlayer\s+from\s*['"][^'"]+['"]/.test(k),j=/import\s*{[^}]*get[^}]*}\s*from\s*['"]svelte\/store['"]/.test(k),M=/const\s+content\s*=\s*useIntlayer\s*\(/.test(k);if(A&&M)return null;let N=A?``:`import { useIntlayer } from '${u}';`,P=O&&!j?`import { get } from 'svelte/store';`:``,F=M?``:`const content = useIntlayer('${v}');`,I=[N,P,F].filter(Boolean);if(I.length===0)return null;let L=`\n ${I.join(`
2
+ `)}\n`;if(D){let e=D.index+D[0].indexOf(`>`)+1;h.appendLeft(e,L)}else h.prepend(`<script>\n ${N}\n ${O?`import { get } from 'svelte/store';`:``}\n ${F}\n<\/script>\n\n`);return p&&p({dictionaryKey:v,filePath:s,content:{...g},locale:l}),{code:h.toString(),map:h.generateMap({source:s,includeContent:!0}),extracted:!0}};exports.ATTRIBUTES_TO_EXTRACT=n,exports.defaultShouldExtract=r,exports.extractDictionaryKeyFromPath=a,exports.generateKey=i,exports.intlayerSvelteExtract=s,exports.shouldProcessFile=o;
244
3
  //# sourceMappingURL=svelte-intlayer-extract.cjs.map