@intlayer/config 9.0.0-canary.11 → 9.0.0-canary.14

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.
Files changed (93) hide show
  1. package/dist/cjs/bundle/index.cjs +1 -1
  2. package/dist/cjs/callers/base.cjs +42 -0
  3. package/dist/cjs/callers/base.cjs.map +1 -0
  4. package/dist/cjs/callers/compat/i18next.cjs +27 -0
  5. package/dist/cjs/callers/compat/i18next.cjs.map +1 -0
  6. package/dist/cjs/callers/compat/lingui.cjs +82 -0
  7. package/dist/cjs/callers/compat/lingui.cjs.map +1 -0
  8. package/dist/cjs/callers/compat/nextIntl.cjs +44 -0
  9. package/dist/cjs/callers/compat/nextIntl.cjs.map +1 -0
  10. package/dist/cjs/callers/compat/reactI18next.cjs +50 -0
  11. package/dist/cjs/callers/compat/reactI18next.cjs.map +1 -0
  12. package/dist/cjs/callers/compat/reactIntl.cjs +31 -0
  13. package/dist/cjs/callers/compat/reactIntl.cjs.map +1 -0
  14. package/dist/cjs/callers/compat/useIntl.cjs +46 -0
  15. package/dist/cjs/callers/compat/useIntl.cjs.map +1 -0
  16. package/dist/cjs/callers/compat/vueI18n.cjs +26 -0
  17. package/dist/cjs/callers/compat/vueI18n.cjs.map +1 -0
  18. package/dist/cjs/callers/index.cjs +87 -0
  19. package/dist/cjs/callers/index.cjs.map +1 -0
  20. package/dist/cjs/callers/transform.cjs +46 -0
  21. package/dist/cjs/callers/transform.cjs.map +1 -0
  22. package/dist/cjs/callers/types.cjs +0 -0
  23. package/dist/cjs/loadEnvFile.cjs +44 -7
  24. package/dist/cjs/loadEnvFile.cjs.map +1 -1
  25. package/dist/cjs/loadExternalFile/index.cjs +1 -0
  26. package/dist/cjs/loadExternalFile/loadExternalFile.cjs +7 -5
  27. package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
  28. package/dist/cjs/loadExternalFile/parseFileContent.cjs +52 -17
  29. package/dist/cjs/loadExternalFile/parseFileContent.cjs.map +1 -1
  30. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +99 -9
  31. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
  32. package/dist/esm/callers/base.mjs +40 -0
  33. package/dist/esm/callers/base.mjs.map +1 -0
  34. package/dist/esm/callers/compat/i18next.mjs +25 -0
  35. package/dist/esm/callers/compat/i18next.mjs.map +1 -0
  36. package/dist/esm/callers/compat/lingui.mjs +80 -0
  37. package/dist/esm/callers/compat/lingui.mjs.map +1 -0
  38. package/dist/esm/callers/compat/nextIntl.mjs +42 -0
  39. package/dist/esm/callers/compat/nextIntl.mjs.map +1 -0
  40. package/dist/esm/callers/compat/reactI18next.mjs +48 -0
  41. package/dist/esm/callers/compat/reactI18next.mjs.map +1 -0
  42. package/dist/esm/callers/compat/reactIntl.mjs +29 -0
  43. package/dist/esm/callers/compat/reactIntl.mjs.map +1 -0
  44. package/dist/esm/callers/compat/useIntl.mjs +44 -0
  45. package/dist/esm/callers/compat/useIntl.mjs.map +1 -0
  46. package/dist/esm/callers/compat/vueI18n.mjs +24 -0
  47. package/dist/esm/callers/compat/vueI18n.mjs.map +1 -0
  48. package/dist/esm/callers/index.mjs +72 -0
  49. package/dist/esm/callers/index.mjs.map +1 -0
  50. package/dist/esm/callers/transform.mjs +43 -0
  51. package/dist/esm/callers/transform.mjs.map +1 -0
  52. package/dist/esm/callers/types.mjs +0 -0
  53. package/dist/esm/loadEnvFile.mjs +45 -8
  54. package/dist/esm/loadEnvFile.mjs.map +1 -1
  55. package/dist/esm/loadExternalFile/index.mjs +2 -2
  56. package/dist/esm/loadExternalFile/loadExternalFile.mjs +7 -5
  57. package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
  58. package/dist/esm/loadExternalFile/parseFileContent.mjs +52 -17
  59. package/dist/esm/loadExternalFile/parseFileContent.mjs.map +1 -1
  60. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +102 -13
  61. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
  62. package/dist/types/callers/base.d.ts +14 -0
  63. package/dist/types/callers/base.d.ts.map +1 -0
  64. package/dist/types/callers/compat/i18next.d.ts +12 -0
  65. package/dist/types/callers/compat/i18next.d.ts.map +1 -0
  66. package/dist/types/callers/compat/lingui.d.ts +7 -0
  67. package/dist/types/callers/compat/lingui.d.ts.map +1 -0
  68. package/dist/types/callers/compat/nextIntl.d.ts +13 -0
  69. package/dist/types/callers/compat/nextIntl.d.ts.map +1 -0
  70. package/dist/types/callers/compat/reactI18next.d.ts +15 -0
  71. package/dist/types/callers/compat/reactI18next.d.ts.map +1 -0
  72. package/dist/types/callers/compat/reactIntl.d.ts +16 -0
  73. package/dist/types/callers/compat/reactIntl.d.ts.map +1 -0
  74. package/dist/types/callers/compat/useIntl.d.ts +12 -0
  75. package/dist/types/callers/compat/useIntl.d.ts.map +1 -0
  76. package/dist/types/callers/compat/vueI18n.d.ts +12 -0
  77. package/dist/types/callers/compat/vueI18n.d.ts.map +1 -0
  78. package/dist/types/callers/index.d.ts +49 -0
  79. package/dist/types/callers/index.d.ts.map +1 -0
  80. package/dist/types/callers/transform.d.ts +57 -0
  81. package/dist/types/callers/transform.d.ts.map +1 -0
  82. package/dist/types/callers/types.d.ts +152 -0
  83. package/dist/types/callers/types.d.ts.map +1 -0
  84. package/dist/types/configFile/configurationSchema.d.ts +2 -2
  85. package/dist/types/loadEnvFile.d.ts +1 -1
  86. package/dist/types/loadEnvFile.d.ts.map +1 -1
  87. package/dist/types/loadExternalFile/index.d.ts +2 -2
  88. package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
  89. package/dist/types/loadExternalFile/parseFileContent.d.ts +9 -0
  90. package/dist/types/loadExternalFile/parseFileContent.d.ts.map +1 -1
  91. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +3 -1
  92. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
  93. package/package.json +7 -2
@@ -0,0 +1,42 @@
1
+ //#region src/callers/compat/nextIntl.ts
2
+ /**
3
+ * next-intl — `@intlayer/next-intl` compat adapter.
4
+ *
5
+ * Mirrors `compat/next-intl/src/plugin/index.ts` (`NEXT_INTL_SWC_CALLERS`),
6
+ * adding the `getTranslations({ locale, namespace })` object overload.
7
+ */
8
+ const NEXT_INTL_CALLERS = [{
9
+ callerName: "useTranslations",
10
+ library: "next-intl",
11
+ importSources: ["next-intl", "@intlayer/next-intl"],
12
+ namespaceSources: [{
13
+ from: "argument",
14
+ index: 0
15
+ }],
16
+ translationFunction: "return-value",
17
+ nestedNamespace: true,
18
+ allowRootScope: true,
19
+ staticReplacement: "useDictionary",
20
+ dynamicReplacement: "useDictionaryDynamic"
21
+ }, {
22
+ callerName: "getTranslations",
23
+ library: "next-intl",
24
+ importSources: ["next-intl/server", "@intlayer/next-intl/server"],
25
+ namespaceSources: [{
26
+ from: "argument",
27
+ index: 0
28
+ }, {
29
+ from: "option",
30
+ argumentIndex: 0,
31
+ property: "namespace"
32
+ }],
33
+ translationFunction: "return-value",
34
+ nestedNamespace: true,
35
+ allowRootScope: true,
36
+ staticReplacement: "getDictionary",
37
+ dynamicReplacement: "getDictionaryDynamic"
38
+ }];
39
+
40
+ //#endregion
41
+ export { NEXT_INTL_CALLERS };
42
+ //# sourceMappingURL=nextIntl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nextIntl.mjs","names":[],"sources":["../../../../src/callers/compat/nextIntl.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * next-intl — `@intlayer/next-intl` compat adapter.\n *\n * Mirrors `compat/next-intl/src/plugin/index.ts` (`NEXT_INTL_SWC_CALLERS`),\n * adding the `getTranslations({ locale, namespace })` object overload.\n */\nexport const NEXT_INTL_CALLERS: CallerDescriptor[] = [\n {\n callerName: 'useTranslations',\n library: 'next-intl',\n importSources: ['next-intl', '@intlayer/next-intl'],\n namespaceSources: [{ from: 'argument', index: 0 }],\n translationFunction: 'return-value',\n // useTranslations('about.counter') → dictionary `about`, prefix `counter`\n nestedNamespace: true,\n // bare useTranslations() → first id segment is the dictionary\n allowRootScope: true,\n staticReplacement: 'useDictionary',\n dynamicReplacement: 'useDictionaryDynamic',\n },\n {\n callerName: 'getTranslations',\n library: 'next-intl',\n importSources: ['next-intl/server', '@intlayer/next-intl/server'],\n // Both overloads: getTranslations('ns') and\n // getTranslations({ locale, namespace: 'ns' }).\n namespaceSources: [\n { from: 'argument', index: 0 },\n { from: 'option', argumentIndex: 0, property: 'namespace' },\n ],\n translationFunction: 'return-value',\n nestedNamespace: true,\n allowRootScope: true,\n staticReplacement: 'getDictionary',\n dynamicReplacement: 'getDictionaryDynamic',\n },\n];\n"],"mappings":";;;;;;;AAQA,MAAa,oBAAwC,CACnD;CACE,YAAY;CACZ,SAAS;CACT,eAAe,CAAC,aAAa,sBAAsB;CACnD,kBAAkB,CAAC;EAAE,MAAM;EAAY,OAAO;EAAG,CAAC;CAClD,qBAAqB;CAErB,iBAAiB;CAEjB,gBAAgB;CAChB,mBAAmB;CACnB,oBAAoB;CACrB,EACD;CACE,YAAY;CACZ,SAAS;CACT,eAAe,CAAC,oBAAoB,6BAA6B;CAGjE,kBAAkB,CAChB;EAAE,MAAM;EAAY,OAAO;EAAG,EAC9B;EAAE,MAAM;EAAU,eAAe;EAAG,UAAU;EAAa,CAC5D;CACD,qBAAqB;CACrB,iBAAiB;CACjB,gBAAgB;CAChB,mBAAmB;CACnB,oBAAoB;CACrB,CACF"}
@@ -0,0 +1,48 @@
1
+ //#region src/callers/compat/reactI18next.ts
2
+ /**
3
+ * react-i18next / next-i18next — `@intlayer/react-i18next` and
4
+ * `@intlayer/next-i18next` compat adapters (next-i18next re-exports the
5
+ * react-i18next hook, so both libraries share the same callers).
6
+ *
7
+ * Mirrors `compat/react-i18next/src/plugin/index.ts` and
8
+ * `compat/next-i18next/src/plugin/index.ts`.
9
+ */
10
+ const REACT_I18NEXT_CALLERS = [{
11
+ callerName: "useTranslation",
12
+ library: "react-i18next",
13
+ importSources: [
14
+ "react-i18next",
15
+ "next-i18next",
16
+ "@intlayer/react-i18next",
17
+ "@intlayer/next-i18next"
18
+ ],
19
+ namespaceSources: [{
20
+ from: "argument",
21
+ index: 0
22
+ }],
23
+ keyPrefixSources: [{
24
+ from: "option",
25
+ argumentIndex: 1,
26
+ property: "keyPrefix"
27
+ }],
28
+ translationFunction: "destructured-t",
29
+ staticReplacement: "useDictionary",
30
+ dynamicReplacement: "useDictionaryDynamic"
31
+ }, {
32
+ callerName: "Trans",
33
+ library: "react-i18next",
34
+ importSources: [
35
+ "react-i18next",
36
+ "next-i18next",
37
+ "@intlayer/react-i18next",
38
+ "@intlayer/next-i18next"
39
+ ],
40
+ jsxIdAttribute: "i18nKey",
41
+ jsxNamespaceAttribute: "ns",
42
+ namespaceSources: [],
43
+ translationFunction: "self"
44
+ }];
45
+
46
+ //#endregion
47
+ export { REACT_I18NEXT_CALLERS };
48
+ //# sourceMappingURL=reactI18next.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reactI18next.mjs","names":[],"sources":["../../../../src/callers/compat/reactI18next.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * react-i18next / next-i18next — `@intlayer/react-i18next` and\n * `@intlayer/next-i18next` compat adapters (next-i18next re-exports the\n * react-i18next hook, so both libraries share the same callers).\n *\n * Mirrors `compat/react-i18next/src/plugin/index.ts` and\n * `compat/next-i18next/src/plugin/index.ts`.\n */\nexport const REACT_I18NEXT_CALLERS: CallerDescriptor[] = [\n {\n callerName: 'useTranslation',\n library: 'react-i18next',\n importSources: [\n 'react-i18next',\n 'next-i18next',\n '@intlayer/react-i18next',\n '@intlayer/next-i18next',\n ],\n namespaceSources: [{ from: 'argument', index: 0 }],\n keyPrefixSources: [\n { from: 'option', argumentIndex: 1, property: 'keyPrefix' },\n ],\n translationFunction: 'destructured-t',\n staticReplacement: 'useDictionary',\n dynamicReplacement: 'useDictionaryDynamic',\n },\n {\n callerName: 'Trans',\n library: 'react-i18next',\n importSources: [\n 'react-i18next',\n 'next-i18next',\n '@intlayer/react-i18next',\n '@intlayer/next-i18next',\n ],\n // <Trans ns=\"home\" i18nKey=\"richText\" /> — the namespace attribute is\n // optional; without it the analyser falls back to the single translator\n // namespace declared in the same file.\n jsxIdAttribute: 'i18nKey',\n jsxNamespaceAttribute: 'ns',\n namespaceSources: [],\n translationFunction: 'self',\n },\n];\n"],"mappings":";;;;;;;;;AAUA,MAAa,wBAA4C,CACvD;CACE,YAAY;CACZ,SAAS;CACT,eAAe;EACb;EACA;EACA;EACA;EACD;CACD,kBAAkB,CAAC;EAAE,MAAM;EAAY,OAAO;EAAG,CAAC;CAClD,kBAAkB,CAChB;EAAE,MAAM;EAAU,eAAe;EAAG,UAAU;EAAa,CAC5D;CACD,qBAAqB;CACrB,mBAAmB;CACnB,oBAAoB;CACrB,EACD;CACE,YAAY;CACZ,SAAS;CACT,eAAe;EACb;EACA;EACA;EACA;EACD;CAID,gBAAgB;CAChB,uBAAuB;CACvB,kBAAkB,EAAE;CACpB,qBAAqB;CACtB,CACF"}
@@ -0,0 +1,29 @@
1
+ //#region src/callers/compat/reactIntl.ts
2
+ /**
3
+ * react-intl (FormatJS) — `@intlayer/react-intl` compat adapter.
4
+ *
5
+ * The full dotted message id encodes both the dictionary key and the field
6
+ * path: `formatMessage({ id: 'home.title' })` → dictionary `home`, field
7
+ * `title`.
8
+ *
9
+ * Mirrors `compat/react-intl/src/plugin/index.ts`.
10
+ */
11
+ const REACT_INTL_CALLERS = [{
12
+ callerName: "formatMessage",
13
+ library: "react-intl",
14
+ importSources: ["react-intl", "@intlayer/react-intl"],
15
+ matchAsMethod: true,
16
+ namespaceSources: [{ from: "path-first-segment" }],
17
+ translationFunction: "self"
18
+ }, {
19
+ callerName: "FormattedMessage",
20
+ library: "react-intl",
21
+ importSources: ["react-intl", "@intlayer/react-intl"],
22
+ jsxIdAttribute: "id",
23
+ namespaceSources: [{ from: "path-first-segment" }],
24
+ translationFunction: "self"
25
+ }];
26
+
27
+ //#endregion
28
+ export { REACT_INTL_CALLERS };
29
+ //# sourceMappingURL=reactIntl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reactIntl.mjs","names":[],"sources":["../../../../src/callers/compat/reactIntl.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * react-intl (FormatJS) — `@intlayer/react-intl` compat adapter.\n *\n * The full dotted message id encodes both the dictionary key and the field\n * path: `formatMessage({ id: 'home.title' })` → dictionary `home`, field\n * `title`.\n *\n * Mirrors `compat/react-intl/src/plugin/index.ts`.\n */\nexport const REACT_INTL_CALLERS: CallerDescriptor[] = [\n {\n callerName: 'formatMessage',\n library: 'react-intl',\n importSources: ['react-intl', '@intlayer/react-intl'],\n // Matches both `intl.formatMessage(...)` and the destructured\n // `const { formatMessage } = useIntl()` identifier form.\n matchAsMethod: true,\n namespaceSources: [{ from: 'path-first-segment' }],\n translationFunction: 'self',\n },\n {\n callerName: 'FormattedMessage',\n library: 'react-intl',\n importSources: ['react-intl', '@intlayer/react-intl'],\n jsxIdAttribute: 'id',\n namespaceSources: [{ from: 'path-first-segment' }],\n translationFunction: 'self',\n },\n];\n"],"mappings":";;;;;;;;;;AAWA,MAAa,qBAAyC,CACpD;CACE,YAAY;CACZ,SAAS;CACT,eAAe,CAAC,cAAc,uBAAuB;CAGrD,eAAe;CACf,kBAAkB,CAAC,EAAE,MAAM,sBAAsB,CAAC;CAClD,qBAAqB;CACtB,EACD;CACE,YAAY;CACZ,SAAS;CACT,eAAe,CAAC,cAAc,uBAAuB;CACrD,gBAAgB;CAChB,kBAAkB,CAAC,EAAE,MAAM,sBAAsB,CAAC;CAClD,qBAAqB;CACtB,CACF"}
@@ -0,0 +1,44 @@
1
+ //#region src/callers/compat/useIntl.ts
2
+ /**
3
+ * use-intl — `@intlayer/use-intl` compat adapter.
4
+ *
5
+ * Mirrors `compat/use-intl/src/plugin/index.ts`.
6
+ */
7
+ const USE_INTL_CALLERS = [{
8
+ callerName: "useTranslations",
9
+ library: "use-intl",
10
+ importSources: [
11
+ "use-intl",
12
+ "use-intl/react",
13
+ "@intlayer/use-intl"
14
+ ],
15
+ namespaceSources: [{
16
+ from: "argument",
17
+ index: 0
18
+ }],
19
+ translationFunction: "return-value",
20
+ nestedNamespace: true,
21
+ allowRootScope: true,
22
+ staticReplacement: "useDictionary",
23
+ dynamicReplacement: "useDictionaryDynamic"
24
+ }, {
25
+ callerName: "createTranslator",
26
+ library: "use-intl",
27
+ importSources: [
28
+ "use-intl",
29
+ "use-intl/core",
30
+ "@intlayer/use-intl"
31
+ ],
32
+ namespaceSources: [{
33
+ from: "option",
34
+ argumentIndex: 0,
35
+ property: "namespace"
36
+ }],
37
+ translationFunction: "return-value",
38
+ nestedNamespace: true,
39
+ allowRootScope: true
40
+ }];
41
+
42
+ //#endregion
43
+ export { USE_INTL_CALLERS };
44
+ //# sourceMappingURL=useIntl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useIntl.mjs","names":[],"sources":["../../../../src/callers/compat/useIntl.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * use-intl — `@intlayer/use-intl` compat adapter.\n *\n * Mirrors `compat/use-intl/src/plugin/index.ts`.\n */\nexport const USE_INTL_CALLERS: CallerDescriptor[] = [\n {\n callerName: 'useTranslations',\n library: 'use-intl',\n importSources: ['use-intl', 'use-intl/react', '@intlayer/use-intl'],\n namespaceSources: [{ from: 'argument', index: 0 }],\n translationFunction: 'return-value',\n // Same namespace semantics as next-intl (next-intl re-exports use-intl).\n nestedNamespace: true,\n allowRootScope: true,\n staticReplacement: 'useDictionary',\n dynamicReplacement: 'useDictionaryDynamic',\n },\n {\n callerName: 'createTranslator',\n library: 'use-intl',\n importSources: ['use-intl', 'use-intl/core', '@intlayer/use-intl'],\n namespaceSources: [\n { from: 'option', argumentIndex: 0, property: 'namespace' },\n ],\n translationFunction: 'return-value',\n nestedNamespace: true,\n allowRootScope: true,\n },\n];\n"],"mappings":";;;;;;AAOA,MAAa,mBAAuC,CAClD;CACE,YAAY;CACZ,SAAS;CACT,eAAe;EAAC;EAAY;EAAkB;EAAqB;CACnE,kBAAkB,CAAC;EAAE,MAAM;EAAY,OAAO;EAAG,CAAC;CAClD,qBAAqB;CAErB,iBAAiB;CACjB,gBAAgB;CAChB,mBAAmB;CACnB,oBAAoB;CACrB,EACD;CACE,YAAY;CACZ,SAAS;CACT,eAAe;EAAC;EAAY;EAAiB;EAAqB;CAClE,kBAAkB,CAChB;EAAE,MAAM;EAAU,eAAe;EAAG,UAAU;EAAa,CAC5D;CACD,qBAAqB;CACrB,iBAAiB;CACjB,gBAAgB;CACjB,CACF"}
@@ -0,0 +1,24 @@
1
+ //#region src/callers/compat/vueI18n.ts
2
+ /**
3
+ * vue-i18n — `@intlayer/vue-i18n` compat adapter.
4
+ *
5
+ * Mirrors `compat/vue-i18n/src/plugin/index.ts`.
6
+ */
7
+ const VUE_I18N_CALLERS = [{
8
+ callerName: "useI18n",
9
+ library: "vue-i18n",
10
+ importSources: ["vue-i18n", "@intlayer/vue-i18n"],
11
+ namespaceSources: [{
12
+ from: "option",
13
+ argumentIndex: 0,
14
+ property: "namespace"
15
+ }],
16
+ translationFunction: "destructured-t",
17
+ allowRootScope: true,
18
+ staticReplacement: "useDictionary",
19
+ dynamicReplacement: "useDictionaryDynamic"
20
+ }];
21
+
22
+ //#endregion
23
+ export { VUE_I18N_CALLERS };
24
+ //# sourceMappingURL=vueI18n.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vueI18n.mjs","names":[],"sources":["../../../../src/callers/compat/vueI18n.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * vue-i18n — `@intlayer/vue-i18n` compat adapter.\n *\n * Mirrors `compat/vue-i18n/src/plugin/index.ts`.\n */\nexport const VUE_I18N_CALLERS: CallerDescriptor[] = [\n {\n callerName: 'useI18n',\n library: 'vue-i18n',\n importSources: ['vue-i18n', '@intlayer/vue-i18n'],\n // `const { t } = useI18n({ namespace: 'ns' })` — the namespace is an\n // intlayer extension of vue-i18n's options object.\n namespaceSources: [\n { from: 'option', argumentIndex: 0, property: 'namespace' },\n ],\n translationFunction: 'destructured-t',\n // Bare `useI18n()` resolves the first key segment as the dictionary:\n // `t('footer.github')` → dictionary `footer`, field `github`.\n allowRootScope: true,\n staticReplacement: 'useDictionary',\n dynamicReplacement: 'useDictionaryDynamic',\n },\n];\n"],"mappings":";;;;;;AAOA,MAAa,mBAAuC,CAClD;CACE,YAAY;CACZ,SAAS;CACT,eAAe,CAAC,YAAY,qBAAqB;CAGjD,kBAAkB,CAChB;EAAE,MAAM;EAAU,eAAe;EAAG,UAAU;EAAa,CAC5D;CACD,qBAAqB;CAGrB,gBAAgB;CAChB,mBAAmB;CACnB,oBAAoB;CACrB,CACF"}
@@ -0,0 +1,72 @@
1
+ import { BASE_CALLERS } from "./base.mjs";
2
+ import { getRewritableCallers, toSwcExtraCallers } from "./transform.mjs";
3
+ import { I18NEXT_CALLERS } from "./compat/i18next.mjs";
4
+ import { LINGUI_CALLERS } from "./compat/lingui.mjs";
5
+ import { NEXT_INTL_CALLERS } from "./compat/nextIntl.mjs";
6
+ import { REACT_I18NEXT_CALLERS } from "./compat/reactI18next.mjs";
7
+ import { REACT_INTL_CALLERS } from "./compat/reactIntl.mjs";
8
+ import { USE_INTL_CALLERS } from "./compat/useIntl.mjs";
9
+ import { VUE_I18N_CALLERS } from "./compat/vueI18n.mjs";
10
+
11
+ //#region src/callers/index.ts
12
+ /**
13
+ * Compat-adapter callers, grouped in one list. Each compat package's bundler
14
+ * plugin injects its own slice (e.g. `REACT_I18NEXT_CALLERS`) into the build
15
+ * pipeline; this aggregate exists for consumers that need every syntax at
16
+ * once, such as the LSP.
17
+ */
18
+ const COMPAT_CALLERS = [
19
+ ...I18NEXT_CALLERS,
20
+ ...REACT_I18NEXT_CALLERS,
21
+ ...NEXT_INTL_CALLERS,
22
+ ...USE_INTL_CALLERS,
23
+ ...REACT_INTL_CALLERS,
24
+ ...LINGUI_CALLERS,
25
+ ...VUE_I18N_CALLERS
26
+ ];
27
+ /** Base + compat callers — the full registry the matchers run against. */
28
+ const ALL_CALLERS = [...BASE_CALLERS, ...COMPAT_CALLERS];
29
+ /**
30
+ * Descriptors indexed by caller name. A name can map to several descriptors
31
+ * (e.g. `Trans` exists in both react-i18next and lingui with different
32
+ * attributes); matchers try them in registry order.
33
+ */
34
+ const CALLERS_BY_NAME = (() => {
35
+ const byName = /* @__PURE__ */ new Map();
36
+ for (const descriptor of ALL_CALLERS) {
37
+ const existing = byName.get(descriptor.callerName);
38
+ if (existing) existing.push(descriptor);
39
+ else byName.set(descriptor.callerName, [descriptor]);
40
+ }
41
+ return byName;
42
+ })();
43
+ /**
44
+ * Caller names whose dictionary key can appear as a positional string literal
45
+ * argument (`caller('key', …)` / `caller(locale, 'key', …)`). Used to build
46
+ * text-search regexes over project source files (find-references) and the
47
+ * completion trigger pattern. Callers whose key never appears positionally
48
+ * (fixed namespace, options object, JSX-only) are excluded on purpose.
49
+ */
50
+ const getPositionalKeyCallerNames = () => {
51
+ const names = /* @__PURE__ */ new Set();
52
+ for (const descriptor of ALL_CALLERS) if (descriptor.namespaceSources.some((source) => source.from === "argument")) names.add(descriptor.callerName);
53
+ return [...names];
54
+ };
55
+ /**
56
+ * Returns `true` when the descriptor may participate in matching for a file
57
+ * importing from `importSources`. Descriptors flagged `requiresImport` only
58
+ * activate when the file imports from one of their declared modules;
59
+ * everything else is always active (results are still validated against the
60
+ * project's dictionaries downstream).
61
+ *
62
+ * @param descriptor - The caller descriptor to gate.
63
+ * @param fileImportSources - Module specifiers imported by the analysed file.
64
+ */
65
+ const isCallerActive = (descriptor, fileImportSources) => {
66
+ if (!descriptor.requiresImport) return true;
67
+ return descriptor.importSources.some((source) => fileImportSources.has(source));
68
+ };
69
+
70
+ //#endregion
71
+ export { ALL_CALLERS, BASE_CALLERS, CALLERS_BY_NAME, COMPAT_CALLERS, I18NEXT_CALLERS, LINGUI_CALLERS, NEXT_INTL_CALLERS, REACT_I18NEXT_CALLERS, REACT_INTL_CALLERS, USE_INTL_CALLERS, VUE_I18N_CALLERS, getPositionalKeyCallerNames, getRewritableCallers, isCallerActive, toSwcExtraCallers };
72
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/callers/index.ts"],"sourcesContent":["import { BASE_CALLERS } from './base';\nimport { I18NEXT_CALLERS } from './compat/i18next';\nimport { LINGUI_CALLERS } from './compat/lingui';\nimport { NEXT_INTL_CALLERS } from './compat/nextIntl';\nimport { REACT_I18NEXT_CALLERS } from './compat/reactI18next';\nimport { REACT_INTL_CALLERS } from './compat/reactIntl';\nimport { USE_INTL_CALLERS } from './compat/useIntl';\nimport { VUE_I18N_CALLERS } from './compat/vueI18n';\nimport type { CallerDescriptor } from './types';\n\nexport { BASE_CALLERS } from './base';\nexport { I18NEXT_CALLERS } from './compat/i18next';\nexport { LINGUI_CALLERS } from './compat/lingui';\nexport { NEXT_INTL_CALLERS } from './compat/nextIntl';\nexport { REACT_I18NEXT_CALLERS } from './compat/reactI18next';\nexport { REACT_INTL_CALLERS } from './compat/reactIntl';\nexport { USE_INTL_CALLERS } from './compat/useIntl';\nexport { VUE_I18N_CALLERS } from './compat/vueI18n';\nexport {\n getRewritableCallers,\n type SwcExtraCallerConfig,\n toSwcExtraCallers,\n} from './transform';\nexport type {\n CallerDescriptor,\n CallerResultShape,\n CallerValueSource,\n} from './types';\n\n/**\n * Compat-adapter callers, grouped in one list. Each compat package's bundler\n * plugin injects its own slice (e.g. `REACT_I18NEXT_CALLERS`) into the build\n * pipeline; this aggregate exists for consumers that need every syntax at\n * once, such as the LSP.\n */\nexport const COMPAT_CALLERS: CallerDescriptor[] = [\n ...I18NEXT_CALLERS,\n ...REACT_I18NEXT_CALLERS,\n ...NEXT_INTL_CALLERS,\n ...USE_INTL_CALLERS,\n ...REACT_INTL_CALLERS,\n ...LINGUI_CALLERS,\n ...VUE_I18N_CALLERS,\n];\n\n/** Base + compat callers — the full registry the matchers run against. */\nexport const ALL_CALLERS: CallerDescriptor[] = [\n ...BASE_CALLERS,\n ...COMPAT_CALLERS,\n];\n\n/**\n * Descriptors indexed by caller name. A name can map to several descriptors\n * (e.g. `Trans` exists in both react-i18next and lingui with different\n * attributes); matchers try them in registry order.\n */\nexport const CALLERS_BY_NAME: Map<string, CallerDescriptor[]> = (() => {\n const byName = new Map<string, CallerDescriptor[]>();\n\n for (const descriptor of ALL_CALLERS) {\n const existing = byName.get(descriptor.callerName);\n\n if (existing) {\n existing.push(descriptor);\n } else {\n byName.set(descriptor.callerName, [descriptor]);\n }\n }\n\n return byName;\n})();\n\n/**\n * Caller names whose dictionary key can appear as a positional string literal\n * argument (`caller('key', …)` / `caller(locale, 'key', …)`). Used to build\n * text-search regexes over project source files (find-references) and the\n * completion trigger pattern. Callers whose key never appears positionally\n * (fixed namespace, options object, JSX-only) are excluded on purpose.\n */\nexport const getPositionalKeyCallerNames = (): string[] => {\n const names = new Set<string>();\n\n for (const descriptor of ALL_CALLERS) {\n const hasPositionalNamespace = descriptor.namespaceSources.some(\n (source) => source.from === 'argument'\n );\n\n if (hasPositionalNamespace) names.add(descriptor.callerName);\n }\n\n return [...names];\n};\n\n/**\n * Returns `true` when the descriptor may participate in matching for a file\n * importing from `importSources`. Descriptors flagged `requiresImport` only\n * activate when the file imports from one of their declared modules;\n * everything else is always active (results are still validated against the\n * project's dictionaries downstream).\n *\n * @param descriptor - The caller descriptor to gate.\n * @param fileImportSources - Module specifiers imported by the analysed file.\n */\nexport const isCallerActive = (\n descriptor: CallerDescriptor,\n fileImportSources: ReadonlySet<string>\n): boolean => {\n if (!descriptor.requiresImport) return true;\n\n return descriptor.importSources.some((source) =>\n fileImportSources.has(source)\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,MAAa,iBAAqC;CAChD,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACJ;;AAGD,MAAa,cAAkC,CAC7C,GAAG,cACH,GAAG,eACJ;;;;;;AAOD,MAAa,yBAA0D;CACrE,MAAM,yBAAS,IAAI,KAAiC;AAEpD,MAAK,MAAM,cAAc,aAAa;EACpC,MAAM,WAAW,OAAO,IAAI,WAAW,WAAW;AAElD,MAAI,SACF,UAAS,KAAK,WAAW;MAEzB,QAAO,IAAI,WAAW,YAAY,CAAC,WAAW,CAAC;;AAInD,QAAO;IACL;;;;;;;;AASJ,MAAa,oCAA8C;CACzD,MAAM,wBAAQ,IAAI,KAAa;AAE/B,MAAK,MAAM,cAAc,YAKvB,KAJ+B,WAAW,iBAAiB,MACxD,WAAW,OAAO,SAAS,WAGJ,CAAE,OAAM,IAAI,WAAW,WAAW;AAG9D,QAAO,CAAC,GAAG,MAAM;;;;;;;;;;;;AAanB,MAAa,kBACX,YACA,sBACY;AACZ,KAAI,CAAC,WAAW,eAAgB,QAAO;AAEvC,QAAO,WAAW,cAAc,MAAM,WACpC,kBAAkB,IAAI,OAAO,CAC9B"}
@@ -0,0 +1,43 @@
1
+ //#region src/callers/transform.ts
2
+ /**
3
+ * Returns the callers of a registry slice that the optimize pass can rewrite
4
+ * at build time: plain imported functions carrying both replacement names.
5
+ *
6
+ * Method-matched callers (`i18n.getFixedT`) and JSX components are excluded —
7
+ * their call sites cannot be re-pointed through an import specifier rename.
8
+ */
9
+ const getRewritableCallers = (descriptors) => descriptors.filter((descriptor) => descriptor.staticReplacement !== void 0 && descriptor.dynamicReplacement !== void 0 && descriptor.matchAsMethod !== true && descriptor.jsxIdAttribute === void 0);
10
+ const findSource = (sources, from) => sources.find((source) => source.from === from);
11
+ /**
12
+ * Serialises the rewritable callers of a registry slice into the
13
+ * `@intlayer/swc` plugin wire format (`extraCallers` option).
14
+ *
15
+ * Callers whose namespace can only be derived per-message id
16
+ * (`path-first-segment`) are skipped: the transform cannot bind a single
17
+ * dictionary to the call site.
18
+ *
19
+ * @param descriptors - Registry slice, e.g. `REACT_I18NEXT_CALLERS`.
20
+ * @returns Configs ready to pass as `swcExtraCallers` / `extraCallers`.
21
+ */
22
+ const toSwcExtraCallers = (descriptors) => getRewritableCallers(descriptors).flatMap((descriptor) => {
23
+ const argumentSource = findSource(descriptor.namespaceSources, "argument");
24
+ const optionSource = findSource(descriptor.namespaceSources, "option");
25
+ const fixedSource = findSource(descriptor.namespaceSources, "fixed");
26
+ if (!argumentSource && !optionSource && !fixedSource) return [];
27
+ return [{
28
+ callerName: descriptor.callerName,
29
+ importSources: descriptor.importSources,
30
+ ...argumentSource ? { namespaceArgIndex: argumentSource.index } : {},
31
+ ...fixedSource ? { fixedNamespace: fixedSource.value } : {},
32
+ ...optionSource ? { namespaceOption: {
33
+ argumentIndex: optionSource.argumentIndex,
34
+ property: optionSource.property
35
+ } } : {},
36
+ staticReplacement: descriptor.staticReplacement,
37
+ dynamicReplacement: descriptor.dynamicReplacement
38
+ }];
39
+ });
40
+
41
+ //#endregion
42
+ export { getRewritableCallers, toSwcExtraCallers };
43
+ //# sourceMappingURL=transform.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform.mjs","names":[],"sources":["../../../src/callers/transform.ts"],"sourcesContent":["import type { CallerDescriptor, CallerValueSource } from './types';\n\n/**\n * Wire format of an extra caller forwarded to the `@intlayer/swc` plugin.\n *\n * Field names mirror the serde attributes of `ExtraCallerConfig` in\n * `packages/@intlayer/swc/src/lib.rs` — both sides must stay in sync.\n */\nexport type SwcExtraCallerConfig = {\n /** The function name the user calls, e.g. `\"useTranslation\"`. */\n callerName: string;\n /** Module specifiers exporting the function (original + `@intlayer/*`). */\n importSources: string[];\n /**\n * Zero-based index of the positional argument holding the namespace string.\n * Omitted for fixed/option namespace callers.\n */\n namespaceArgIndex?: number;\n /**\n * Compile-time constant namespace — the dictionary ident is inserted as a\n * new first argument (lingui's `useLingui()`).\n */\n fixedNamespace?: string;\n /**\n * Namespace read from a property of an options-object argument — the\n * dictionary ident is inserted as a new first argument and the property is\n * rewritten to the key-prefix remainder (vue-i18n's `useI18n({ namespace })`).\n */\n namespaceOption?: { argumentIndex: number; property: string };\n /** Replacement function name for static import mode, e.g. `\"useDictionary\"`. */\n staticReplacement: string;\n /** Replacement function name for dynamic/fetch mode, e.g. `\"useDictionaryDynamic\"`. */\n dynamicReplacement: string;\n};\n\n/**\n * Returns the callers of a registry slice that the optimize pass can rewrite\n * at build time: plain imported functions carrying both replacement names.\n *\n * Method-matched callers (`i18n.getFixedT`) and JSX components are excluded —\n * their call sites cannot be re-pointed through an import specifier rename.\n */\nexport const getRewritableCallers = (\n descriptors: CallerDescriptor[]\n): CallerDescriptor[] =>\n descriptors.filter(\n (descriptor) =>\n descriptor.staticReplacement !== undefined &&\n descriptor.dynamicReplacement !== undefined &&\n descriptor.matchAsMethod !== true &&\n descriptor.jsxIdAttribute === undefined\n );\n\nconst findSource = <F extends CallerValueSource['from']>(\n sources: CallerValueSource[],\n from: F\n): Extract<CallerValueSource, { from: F }> | undefined =>\n sources.find(\n (source): source is Extract<CallerValueSource, { from: F }> =>\n source.from === from\n );\n\n/**\n * Serialises the rewritable callers of a registry slice into the\n * `@intlayer/swc` plugin wire format (`extraCallers` option).\n *\n * Callers whose namespace can only be derived per-message id\n * (`path-first-segment`) are skipped: the transform cannot bind a single\n * dictionary to the call site.\n *\n * @param descriptors - Registry slice, e.g. `REACT_I18NEXT_CALLERS`.\n * @returns Configs ready to pass as `swcExtraCallers` / `extraCallers`.\n */\nexport const toSwcExtraCallers = (\n descriptors: CallerDescriptor[]\n): SwcExtraCallerConfig[] =>\n getRewritableCallers(descriptors).flatMap((descriptor) => {\n const argumentSource = findSource(descriptor.namespaceSources, 'argument');\n const optionSource = findSource(descriptor.namespaceSources, 'option');\n const fixedSource = findSource(descriptor.namespaceSources, 'fixed');\n\n if (!argumentSource && !optionSource && !fixedSource) return [];\n\n return [\n {\n callerName: descriptor.callerName,\n importSources: descriptor.importSources,\n ...(argumentSource ? { namespaceArgIndex: argumentSource.index } : {}),\n ...(fixedSource ? { fixedNamespace: fixedSource.value } : {}),\n ...(optionSource\n ? {\n namespaceOption: {\n argumentIndex: optionSource.argumentIndex,\n property: optionSource.property,\n },\n }\n : {}),\n staticReplacement: descriptor.staticReplacement!,\n dynamicReplacement: descriptor.dynamicReplacement!,\n },\n ];\n });\n"],"mappings":";;;;;;;;AA0CA,MAAa,wBACX,gBAEA,YAAY,QACT,eACC,WAAW,sBAAsB,UACjC,WAAW,uBAAuB,UAClC,WAAW,kBAAkB,QAC7B,WAAW,mBAAmB,OACjC;AAEH,MAAM,cACJ,SACA,SAEA,QAAQ,MACL,WACC,OAAO,SAAS,KACnB;;;;;;;;;;;;AAaH,MAAa,qBACX,gBAEA,qBAAqB,YAAY,CAAC,SAAS,eAAe;CACxD,MAAM,iBAAiB,WAAW,WAAW,kBAAkB,WAAW;CAC1E,MAAM,eAAe,WAAW,WAAW,kBAAkB,SAAS;CACtE,MAAM,cAAc,WAAW,WAAW,kBAAkB,QAAQ;AAEpE,KAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,YAAa,QAAO,EAAE;AAE/D,QAAO,CACL;EACE,YAAY,WAAW;EACvB,eAAe,WAAW;EAC1B,GAAI,iBAAiB,EAAE,mBAAmB,eAAe,OAAO,GAAG,EAAE;EACrE,GAAI,cAAc,EAAE,gBAAgB,YAAY,OAAO,GAAG,EAAE;EAC5D,GAAI,eACA,EACE,iBAAiB;GACf,eAAe,aAAa;GAC5B,UAAU,aAAa;GACxB,EACF,GACD,EAAE;EACN,mBAAmB,WAAW;EAC9B,oBAAoB,WAAW;EAChC,CACF;EACD"}
File without changes
@@ -1,4 +1,4 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, statSync } from "node:fs";
2
2
  import dotenv from "dotenv";
3
3
 
4
4
  //#region src/loadEnvFile.ts
@@ -11,16 +11,53 @@ const getEnvFilePath = (env = "development", envFile) => {
11
11
  ".env"
12
12
  ]).find(existsSync);
13
13
  };
14
- const loadEnvFile = (options) => {
15
- const envFiles = getEnvFilePath(options?.env ?? DEFAULT_ENV, options?.envFile);
16
- if (!envFiles) return {};
17
- const result = {};
14
+ /**
15
+ * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content
16
+ * declarations calls `loadEnvFile` once per file; without this every call pays
17
+ * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is
18
+ * validated with a single `stat` so edits to the env file are still picked up.
19
+ */
20
+ const envFileCache = /* @__PURE__ */ new Map();
21
+ const parseEnvFile = (envFilePath) => {
22
+ const parsedEnv = {};
18
23
  dotenv.config({
19
- path: envFiles,
20
- processEnv: result,
24
+ path: envFilePath,
25
+ processEnv: parsedEnv,
21
26
  quiet: true
22
27
  });
23
- return result;
28
+ return parsedEnv;
29
+ };
30
+ const loadEnvFile = (options) => {
31
+ const env = options?.env ?? DEFAULT_ENV;
32
+ const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ""}`;
33
+ const cachedEntry = envFileCache.get(cacheKey);
34
+ if (cachedEntry) if (cachedEntry.envFilePath === void 0) {
35
+ if (!getEnvFilePath(env, options?.envFile)) return cachedEntry.parsedEnv;
36
+ } else try {
37
+ const stats = statSync(cachedEntry.envFilePath);
38
+ if (stats.mtimeMs === cachedEntry.mtimeMs && stats.size === cachedEntry.size) return cachedEntry.parsedEnv;
39
+ } catch {}
40
+ const envFilePath = getEnvFilePath(env, options?.envFile);
41
+ if (!envFilePath) {
42
+ envFileCache.set(cacheKey, {
43
+ envFilePath: void 0,
44
+ mtimeMs: 0,
45
+ size: 0,
46
+ parsedEnv: {}
47
+ });
48
+ return {};
49
+ }
50
+ const parsedEnv = parseEnvFile(envFilePath);
51
+ try {
52
+ const stats = statSync(envFilePath);
53
+ envFileCache.set(cacheKey, {
54
+ envFilePath,
55
+ mtimeMs: stats.mtimeMs,
56
+ size: stats.size,
57
+ parsedEnv
58
+ });
59
+ } catch {}
60
+ return parsedEnv;
24
61
  };
25
62
 
26
63
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\nexport const loadEnvFile = (options?: Partial<LoadEnvFileOptions>) => {\n const env = options?.env ?? DEFAULT_ENV;\n\n const envFiles = getEnvFilePath(env, options?.envFile);\n\n if (!envFiles) {\n return {};\n }\n\n const result = {};\n\n dotenv.config({\n path: envFiles,\n processEnv: result,\n quiet: true,\n });\n\n return result; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;AAKvB,SAJiB,UACb,CAAC,QAAQ,GACT;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;EAAO,EAE9C,KAAK,WAAW;;AAGlC,MAAa,eAAe,YAA0C;CAGpE,MAAM,WAAW,eAFL,SAAS,OAAO,aAES,SAAS,QAAQ;AAEtD,KAAI,CAAC,SACH,QAAO,EAAE;CAGX,MAAM,SAAS,EAAE;AAEjB,QAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;EACR,CAAC;AAEF,QAAO"}
1
+ {"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;AAKvB,SAJiB,UACb,CAAC,QAAQ,GACT;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;EAAO,EAE9C,KAAK,WAAW;;;;;;;;AAmBlC,MAAM,+BAAe,IAAI,KAAgC;AAEzD,MAAM,gBAAgB,gBAAgD;CACpE,MAAM,YAAoC,EAAE;AAE5C,QAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;EACR,CAAC;AAEF,QAAO;;AAGT,MAAa,eACX,YAC2B;CAC3B,MAAM,MAAM,SAAS,OAAO;CAG5B,MAAM,WAAW,GAAG,QAAQ,KAAK,CAAC,GAAG,IAAI,GAAG,SAAS,WAAW;CAEhE,MAAM,cAAc,aAAa,IAAI,SAAS;AAE9C,KAAI,YACF,KAAI,YAAY,gBAAgB,QAG9B;MAAI,CADgB,eAAe,KAAK,SAAS,QACjC,CAAE,QAAO,YAAY;OAErC,KAAI;EACF,MAAM,QAAQ,SAAS,YAAY,YAAY;AAC/C,MACE,MAAM,YAAY,YAAY,WAC9B,MAAM,SAAS,YAAY,KAE3B,QAAO,YAAY;SAEf;CAMZ,MAAM,cAAc,eAAe,KAAK,SAAS,QAAQ;AAEzD,KAAI,CAAC,aAAa;AAChB,eAAa,IAAI,UAAU;GACzB,aAAa;GACb,SAAS;GACT,MAAM;GACN,WAAW,EAAE;GACd,CAAC;AACF,SAAO,EAAE;;CAGX,MAAM,YAAY,aAAa,YAAY;AAE3C,KAAI;EACF,MAAM,QAAQ,SAAS,YAAY;AACnC,eAAa,IAAI,UAAU;GACzB;GACA,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;GACD,CAAC;SACI;AAIR,QAAO"}
@@ -1,7 +1,7 @@
1
1
  import { getSandBoxContext, parseFileContent } from "./parseFileContent.mjs";
2
2
  import { bundleFile, bundleFileSync, getLoader } from "./bundleFile.mjs";
3
- import { transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
3
+ import { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
4
4
  import { loadExternalFile, loadExternalFileSync } from "./loadExternalFile.mjs";
5
5
  import { bundleJSFile } from "./bundleJSFile.mjs";
6
6
 
7
- export { bundleFile, bundleFileSync, bundleJSFile, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
7
+ export { bundleFile, bundleFileSync, bundleJSFile, clearTranspileCache, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
@@ -22,13 +22,13 @@ const loadExternalFileSync = (filePath, options) => {
22
22
  logger("File could not be loaded.", { level: "error" });
23
23
  return;
24
24
  }
25
- const fileContent = parseFileContent(moduleResultString, {
25
+ const fileContent = withPreloadedGlobals(options?.preloadGlobals, () => parseFileContent(moduleResultString, {
26
26
  projectRequire: options?.projectRequire,
27
27
  envVarOptions: options?.envVarOptions,
28
28
  additionalEnvVars: options?.additionalEnvVars,
29
29
  mocks: options?.mocks,
30
30
  aliases: options?.aliases
31
- });
31
+ }));
32
32
  if (typeof fileContent === "undefined") {
33
33
  logger(`File could not be loaded. Path : ${filePath}`);
34
34
  return;
@@ -41,15 +41,17 @@ const loadExternalFileSync = (filePath, options) => {
41
41
  const withPreloadedGlobals = (globals, fn) => {
42
42
  if (!globals) return fn();
43
43
  const globalVars = globalThis;
44
- const prev = {};
44
+ const previousValues = {};
45
+ const previouslyPresent = {};
45
46
  for (const [key, value] of Object.entries(globals)) {
46
- prev[key] = globalVars[key];
47
+ previouslyPresent[key] = key in globalVars;
48
+ previousValues[key] = globalVars[key];
47
49
  globalVars[key] = value;
48
50
  }
49
51
  try {
50
52
  return fn();
51
53
  } finally {
52
- for (const key of Object.keys(globals)) if (prev[key] !== void 0) globalVars[key] = prev[key];
54
+ for (const key of Object.keys(globals)) if (previouslyPresent[key]) globalVars[key] = previousValues[key];
53
55
  else delete globalVars[key];
54
56
  }
55
57
  };
@@ -1 +1 @@
1
- {"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n const fileContent = parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n });\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const prev: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n prev[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n if (prev[key] !== undefined) {\n globalVars[key] = prev[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,SAAS,IAAI;AAE3C,KAAI;AACF,MACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,SAGlB,QAAO,WAAW,aAAa,UAAU,QAAQ,CAAC;EAMpD,MAAM,qBAAyC,qBAFlC,aAAa,UAAU,QAG9B,EACJ,UACA,SAAS,aACV;AAED,MAAI,CAAC,oBAAoB;AACvB,UAAO,6BAA6B,EAAE,OAAO,SAAS,CAAC;AACvD;;EAGF,MAAM,cAAc,iBAAiB,oBAAoB;GACvD,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;GACnB,CAAC;AAEF,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAO,oCAAoC,WAAW;AACtD;;AAGF,SAAO;UACA,OAAO;AACd,SACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,EAAE,CAChD,EACD,EACE,OAAO,SACR,CACF;;;AAIL,MAAM,wBACJ,SACA,OACM;AACN,KAAI,CAAC,QAAS,QAAO,IAAI;CAEzB,MAAM,aAAa;CACnB,MAAM,OAAgC,EAAE;AAExC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,OAAK,OAAO,WAAW;AACvB,aAAW,OAAO;;AAGpB,KAAI;AACF,SAAO,IAAI;WACH;AACR,OAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,CACpC,KAAI,KAAK,SAAS,OAChB,YAAW,OAAO,KAAK;MAEvB,QAAO,WAAW;;;;;;;;AAW1B,MAAa,mBAAmB,OAC9B,UACA,YAC6B;CAC7B,MAAM,gBAAgB,QAAQ,SAAS;AAEvC,KAAI;AACF,MACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,SAIlB,QAAO,WAAW,MADQ,SAAS,UAAU,QAAQ,CACvB;EAMhC,MAAM,qBAAyC,MAAM,iBACnD,MAHiB,SAAS,UAAU,QAAQ,EAI5C,UACA,SAAS,aACV;AAED,MAAI,CAAC,oBAAoB;AACvB,UAAO,6BAA6B,EAAE,OAAO,SAAS,CAAC;AACvD;;EAKF,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;GACnB,CAAC,CACH;AAED,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAO,oCAAoC,aAAa,SAAS,GAAG;AACpE;;AAGF,SAAO;UACA,OAAO;AACd,MAAI,SAAS,YAAY,KACvB,QACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,EAAE,CAChD,EACD,EACE,OAAO,SACR,CACF"}
1
+ {"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,SAAS,IAAI;AAE3C,KAAI;AACF,MACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,SAGlB,QAAO,WAAW,aAAa,UAAU,QAAQ,CAAC;EAMpD,MAAM,qBAAyC,qBAFlC,aAAa,UAAU,QAG9B,EACJ,UACA,SAAS,aACV;AAED,MAAI,CAAC,oBAAoB;AACvB,UAAO,6BAA6B,EAAE,OAAO,SAAS,CAAC;AACvD;;EAKF,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;GACnB,CAAC,CACH;AAED,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAO,oCAAoC,WAAW;AACtD;;AAGF,SAAO;UACA,OAAO;AACd,SACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,EAAE,CAChD,EACD,EACE,OAAO,SACR,CACF;;;AAIL,MAAM,wBACJ,SACA,OACM;AACN,KAAI,CAAC,QAAS,QAAO,IAAI;CAEzB,MAAM,aAAa;CACnB,MAAM,iBAA0C,EAAE;CAClD,MAAM,oBAA6C,EAAE;AAErD,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,oBAAkB,OAAO,OAAO;AAChC,iBAAe,OAAO,WAAW;AACjC,aAAW,OAAO;;AAGpB,KAAI;AACF,SAAO,IAAI;WACH;AACR,OAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,CAGpC,KAAI,kBAAkB,KACpB,YAAW,OAAO,eAAe;MAEjC,QAAO,WAAW;;;;;;;;AAW1B,MAAa,mBAAmB,OAC9B,UACA,YAC6B;CAC7B,MAAM,gBAAgB,QAAQ,SAAS;AAEvC,KAAI;AACF,MACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,SAIlB,QAAO,WAAW,MADQ,SAAS,UAAU,QAAQ,CACvB;EAMhC,MAAM,qBAAyC,MAAM,iBACnD,MAHiB,SAAS,UAAU,QAAQ,EAI5C,UACA,SAAS,aACV;AAED,MAAI,CAAC,oBAAoB;AACvB,UAAO,6BAA6B,EAAE,OAAO,SAAS,CAAC;AACvD;;EAKF,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;GACnB,CAAC,CACH;AAED,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAO,oCAAoC,aAAa,SAAS,GAAG;AACpE;;AAGF,SAAO;UACA,OAAO;AACd,MAAI,SAAS,YAAY,KACvB,QACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,EAAE,CAChD,EACD,EACE,OAAO,SACR,CACF"}
@@ -24,9 +24,58 @@ const NODE_GLOBALS = [
24
24
  "crypto",
25
25
  "structuredClone"
26
26
  ];
27
+ /**
28
+ * Cache of the project's React module (or the JSX-capturing fallback) keyed by
29
+ * the require's resolution paths. Node does not cache *failed* resolutions, so
30
+ * without this every sandbox creation in a non-React project (Vue, Svelte,
31
+ * Angular…) pays a full node_modules walk that ends in a throw.
32
+ */
33
+ const reactModuleCache = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Fallback React implementation used when React is not installed in the
36
+ * project. It captures JSX elements as plain objects so JSX can be used in
37
+ * content declarations (esbuild's tsx loader defaults to React.createElement).
38
+ */
39
+ const createFallbackReact = () => ({
40
+ createElement: (type, props, ...children) => ({
41
+ type,
42
+ props: {
43
+ ...props,
44
+ children: children.length <= 1 ? children[0] : children
45
+ }
46
+ }),
47
+ Fragment: Symbol.for("react.fragment")
48
+ });
49
+ const getReactGlobal = (baseRequire) => {
50
+ const resolutionKey = baseRequire.resolve.paths?.("react")?.join("|") ?? "<default>";
51
+ const cachedReactModule = reactModuleCache.get(resolutionKey);
52
+ if (cachedReactModule) return cachedReactModule;
53
+ let reactGlobal;
54
+ try {
55
+ reactGlobal = { React: baseRequire("react") };
56
+ } catch (_err) {
57
+ reactGlobal = { React: createFallbackReact() };
58
+ }
59
+ reactModuleCache.set(resolutionKey, reactGlobal);
60
+ return reactGlobal;
61
+ };
62
+ /**
63
+ * Snapshot of the non-env `process` properties, taken once at module load.
64
+ * Spreading `process` enumerates ~100 properties (some behind getters); doing
65
+ * it per sandbox is wasteful since everything except `env` is static.
66
+ */
67
+ const processSnapshot = { ...process };
68
+ /**
69
+ * Builds the global context handed to `runInNewContext`.
70
+ *
71
+ * SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh
72
+ * module/exports, controlled env), NOT for containment. It exposes the real
73
+ * project `require`, a copy of `process`, and `fetch` — code executed here has
74
+ * full host privileges. Only ever run trusted, build-time project files
75
+ * (same trust model as `vite.config.ts`).
76
+ */
27
77
  const getSandBoxContext = (options) => {
28
78
  const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } = options ?? {};
29
- let additionalGlobalVar = {};
30
79
  const baseRequire = typeof projectRequire === "function" ? projectRequire : getProjectRequire();
31
80
  const mockedRequire = (() => {
32
81
  const mockTable = Object.assign({ esbuild }, mocks);
@@ -43,25 +92,11 @@ const getSandBoxContext = (options) => {
43
92
  wrappedRequire.cache = baseRequire.cache;
44
93
  return wrappedRequire;
45
94
  })();
46
- try {
47
- additionalGlobalVar = { React: baseRequire("react") };
48
- } catch (_err) {
49
- additionalGlobalVar = { React: {
50
- createElement: (type, props, ...children) => ({
51
- type,
52
- props: {
53
- ...props,
54
- children: children.length <= 1 ? children[0] : children
55
- }
56
- }),
57
- Fragment: Symbol.for("react.fragment")
58
- } };
59
- }
60
95
  const sandboxContext = {
61
96
  exports: { default: {} },
62
97
  module: { exports: {} },
63
98
  process: {
64
- ...process,
99
+ ...processSnapshot,
65
100
  env: {
66
101
  ...process.env,
67
102
  ...loadEnvFile(envVarOptions),
@@ -70,7 +105,7 @@ const getSandBoxContext = (options) => {
70
105
  },
71
106
  console,
72
107
  require: mockedRequire,
73
- ...additionalGlobalVar
108
+ ...getReactGlobal(baseRequire)
74
109
  };
75
110
  for (const key of NODE_GLOBALS) if (!(key in sandboxContext) && key in globalThis) sandboxContext[key] = globalThis[key];
76
111
  return sandboxContext;