@servicetitan/startup 39.0.1 → 39.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/vite/build-escaped-reg-exp.d.ts +2 -0
  2. package/dist/vite/build-escaped-reg-exp.d.ts.map +1 -0
  3. package/dist/vite/build-escaped-reg-exp.js +16 -0
  4. package/dist/vite/build-escaped-reg-exp.js.map +1 -0
  5. package/dist/vite/config/base-config.d.ts.map +1 -1
  6. package/dist/vite/config/base-config.js +7 -2
  7. package/dist/vite/config/base-config.js.map +1 -1
  8. package/dist/vite/config/create-resolve-config.d.ts +6 -0
  9. package/dist/vite/config/create-resolve-config.d.ts.map +1 -0
  10. package/dist/vite/config/create-resolve-config.js +52 -0
  11. package/dist/vite/config/create-resolve-config.js.map +1 -0
  12. package/dist/vite/plugins/css-injector-plugin.d.ts.map +1 -1
  13. package/dist/vite/plugins/css-injector-plugin.js +5 -1
  14. package/dist/vite/plugins/css-injector-plugin.js.map +1 -1
  15. package/dist/vite/plugins/externals-plugin.d.ts.map +1 -1
  16. package/dist/vite/plugins/externals-plugin.js +3 -3
  17. package/dist/vite/plugins/externals-plugin.js.map +1 -1
  18. package/package.json +6 -6
  19. package/src/vite/__tests__/build-escaped-reg-exp.test.ts +25 -0
  20. package/src/vite/build-escaped-reg-exp.ts +6 -0
  21. package/src/vite/config/__tests__/base-config.test.ts +1 -1
  22. package/src/vite/config/__tests__/create-resolve-config.test.ts +85 -0
  23. package/src/vite/config/base-config.ts +4 -2
  24. package/src/vite/config/create-resolve-config.ts +43 -0
  25. package/src/vite/plugins/__tests__/css-injector-plugin.test.ts +1 -1
  26. package/src/vite/plugins/css-injector-plugin.ts +6 -1
  27. package/src/vite/plugins/externals-plugin.ts +1 -4
@@ -0,0 +1,2 @@
1
+ export declare const buildEscapedRegExp: (specifier: string) => RegExp;
2
+ //# sourceMappingURL=build-escaped-reg-exp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-escaped-reg-exp.d.ts","sourceRoot":"","sources":["../../src/vite/build-escaped-reg-exp.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,kBAAkB,GAAI,WAAW,MAAM,WACM,CAAC"}
@@ -0,0 +1,16 @@
1
+ /*
2
+ * Dots are the only regex-special character valid in a package name; the
3
+ * backslash is escaped because it is the escape character itself.
4
+ */ "use strict";
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ Object.defineProperty(exports, "buildEscapedRegExp", {
9
+ enumerable: true,
10
+ get: function() {
11
+ return buildEscapedRegExp;
12
+ }
13
+ });
14
+ const buildEscapedRegExp = (specifier)=>new RegExp(`^${specifier.replace(/[\\.]/g, '\\$&')}$`);
15
+
16
+ //# sourceMappingURL=build-escaped-reg-exp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/vite/build-escaped-reg-exp.ts"],"sourcesContent":["/*\n * Dots are the only regex-special character valid in a package name; the\n * backslash is escaped because it is the escape character itself.\n */\nexport const buildEscapedRegExp = (specifier: string) =>\n new RegExp(`^${specifier.replace(/[\\\\.]/g, '\\\\$&')}$`);\n"],"names":["buildEscapedRegExp","specifier","RegExp","replace"],"mappings":"AAAA;;;CAGC;;;;+BACYA;;;eAAAA;;;AAAN,MAAMA,qBAAqB,CAACC,YAC/B,IAAIC,OAAO,CAAC,CAAC,EAAED,UAAUE,OAAO,CAAC,UAAU,QAAQ,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"base-config.d.ts","sourceRoot":"","sources":["../../../src/vite/config/base-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAU,MAAM,MAAM,CAAC;AA8BjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAkD5C,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,GAAG,YAAY,CAgFxE"}
1
+ {"version":3,"file":"base-config.d.ts","sourceRoot":"","sources":["../../../src/vite/config/base-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAU,MAAM,MAAM,CAAC;AA8BjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAmD5C,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,GAAG,YAAY,CAiFxE"}
@@ -15,6 +15,7 @@ const _assetfilenames = require("./asset-file-names");
15
15
  const _codesplitting = require("./code-splitting");
16
16
  const _createcssconfig = require("./create-css-config");
17
17
  const _createfilteringlogger = require("./create-filtering-logger");
18
+ const _createresolveconfig = require("./create-resolve-config");
18
19
  function importMetaRemap(...definitions) {
19
20
  const result = {};
20
21
  definitions.filter((definition)=>definition !== undefined).forEach((definition)=>Object.keys(definition).forEach((item)=>{
@@ -97,6 +98,10 @@ function createPlugins(context) {
97
98
  function createBaseConfig(context) {
98
99
  var _getBundleType, _context_bundlerConfig_port, _getProcessEnv;
99
100
  var _context_bundlerConfig_omitDefault;
101
+ const optimizedStartupDependencies = [
102
+ '@servicetitan/startup-utils',
103
+ 'react-refresh/runtime'
104
+ ];
100
105
  const { isProduction } = context.build;
101
106
  const { isWebComponent } = context.package;
102
107
  let config = {
@@ -138,10 +143,10 @@ function createBaseConfig(context) {
138
143
  ...importMetaRemap((0, _core.defineExposedDependencies)(context), (0, _core.defineExposedInstanceDependencies)(context), (0, _core.defineWebComponentName)(context)),
139
144
  ...(_getProcessEnv = (0, _core.getProcessEnv)(context)) !== null && _getProcessEnv !== void 0 ? _getProcessEnv : {}
140
145
  },
146
+ resolve: (0, _createresolveconfig.createResolveConfig)(context, optimizedStartupDependencies),
141
147
  optimizeDeps: {
142
148
  include: [
143
- '@servicetitan/startup-utils',
144
- 'react-refresh/runtime',
149
+ ...optimizedStartupDependencies,
145
150
  'react/jsx-runtime',
146
151
  'react/jsx-dev-runtime'
147
152
  ],
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/vite/config/base-config.ts"],"sourcesContent":["import type { InlineConfig, Plugin } from 'vite';\nimport {\n bundleConstants,\n defineExposedDependencies,\n defineExposedInstanceDependencies,\n defineWebComponentName,\n getBundleType,\n getCdnPath,\n getProcessEnv,\n} from '../../core';\nimport { omit } from '../../utils';\nimport {\n bundleStatPlugin,\n chainSourceMapsPlugin,\n cleanPlugin,\n cssInjectorPlugin,\n designSystemGuardPlugin,\n devServerRoutingPlugin,\n externalsPlugin,\n htmlPlugin,\n ignoreModulesPlugin,\n istanbulPlugin,\n magicCommentsPlugin,\n metadataPlugin,\n momentLocalesPlugin,\n reactRefreshPlugin,\n styleUrlsPlugin,\n svgrPlugin,\n virtualModulesPlugin,\n} from '../plugins';\nimport { ViteBuildContext } from '../types';\nimport { assetFileNames } from './asset-file-names';\nimport { getCodeSplitting } from './code-splitting';\nimport { createCssConfig } from './create-css-config';\nimport { createFilteringLogger } from './create-filtering-logger';\n\nfunction importMetaRemap(\n ...definitions: (Record<string, string> | undefined)[]\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n definitions\n .filter(definition => definition !== undefined)\n .forEach(definition =>\n Object.keys(definition).forEach(item => {\n result[`import.meta.env.${item}`] = definition[item];\n })\n );\n\n return result;\n}\n\nfunction createPlugins(context: ViteBuildContext) {\n const entries: [string, Plugin[] | Plugin | Promise<Plugin> | undefined][] = [\n ['reactRefresh', reactRefreshPlugin(context)],\n ['bundleStat', bundleStatPlugin(context)],\n ['clean', cleanPlugin(context)],\n ['cssInjector', cssInjectorPlugin(context)],\n ['designSystemGuard', designSystemGuardPlugin(context)],\n ['devServerRouting', devServerRoutingPlugin(context)],\n ['externals', externalsPlugin(context)],\n ['html', htmlPlugin(context)],\n ['ignoreModules', ignoreModulesPlugin(context)],\n ['istanbul', istanbulPlugin(context)],\n ['magicComments', magicCommentsPlugin(context)],\n ['metadata', metadataPlugin(context)],\n ['momentLocales', momentLocalesPlugin(context)],\n ['styleUrls', styleUrlsPlugin(context)],\n ['svgr', svgrPlugin(context)],\n ['virtualModules', virtualModulesPlugin(context)],\n ];\n\n return entries\n .filter(\n ([name, plugin]) =>\n plugin && !context.bundlerConfig.omitDefault?.includes(`plugins.${name}`)\n )\n .flatMap(([, plugin]) => plugin);\n}\n\nexport function createBaseConfig(context: ViteBuildContext): InlineConfig {\n const { isProduction } = context.build;\n const { isWebComponent } = context.package;\n\n let config: InlineConfig = {\n cacheDir: `node_modules/.vite/${getBundleType(context) ?? 'host'}`,\n customLogger: createFilteringLogger(),\n server: {\n // Windows machines can fail to connect to \"localhost\"; bind to a fixed address instead.\n host: '127.0.0.1',\n port: context.bundlerConfig.port ?? (isWebComponent ? 8888 : 8080),\n },\n mode: isProduction ? bundleConstants.mode.production : bundleConstants.mode.development,\n configFile: false,\n oxc: { legalComments: 'none' },\n base: getCdnPath(context) || './', // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing\n css: createCssConfig(isProduction),\n build: {\n /*\n * MFEs render inside shadow DOM — lazy CSS chunks would inject into document.head,\n * leaking styles into the host. Bundling all CSS into one file avoids this.\n */\n cssCodeSplit: !isWebComponent,\n sourcemap: true,\n rolldownOptions: {\n output: { assetFileNames, codeSplitting: getCodeSplitting(context) },\n plugins: [chainSourceMapsPlugin()],\n },\n },\n define: {\n /*\n * Some dependencies assume Node's `global` exists (webpack polyfills this\n * automatically for browser targets; Vite does not).\n */\n global: 'globalThis',\n ...importMetaRemap(\n defineExposedDependencies(context),\n defineExposedInstanceDependencies(context),\n defineWebComponentName(context)\n ),\n ...(getProcessEnv(context) ?? {}),\n },\n optimizeDeps: {\n include: [\n '@servicetitan/startup-utils',\n 'react-refresh/runtime',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n ],\n /*\n * Top-level plugins don't run during dependency pre-bundling, so\n * register ignoreModulesPlugin again here. Without this, missing\n * optional peer dependencies inside pre-bundled packages throw at\n * runtime instead of resolving to an empty module.\n */\n rolldownOptions: {\n plugins: [ignoreModulesPlugin(context)],\n },\n },\n plugins: createPlugins(context),\n };\n\n const omitKeys = context.bundlerConfig.omitDefault?.filter(k => !k.startsWith('plugins.'));\n if (omitKeys?.length) {\n config = omit({ ...config }, omitKeys);\n }\n\n if (context.bundlerConfig.minify.js !== undefined) {\n config.build = { ...config.build, minify: !!context.bundlerConfig.minify.js };\n }\n if (context.bundlerConfig.minify.css !== undefined) {\n config.build = { ...config.build, cssMinify: !!context.bundlerConfig.minify.css };\n }\n\n // Minified output can't be mapped back to source, so skip it when instrumenting.\n if (context.options.codeCoverage) {\n config.build = { ...config.build, minify: false };\n }\n\n return config;\n}\n"],"names":["createBaseConfig","importMetaRemap","definitions","result","filter","definition","undefined","forEach","Object","keys","item","createPlugins","context","entries","reactRefreshPlugin","bundleStatPlugin","cleanPlugin","cssInjectorPlugin","designSystemGuardPlugin","devServerRoutingPlugin","externalsPlugin","htmlPlugin","ignoreModulesPlugin","istanbulPlugin","magicCommentsPlugin","metadataPlugin","momentLocalesPlugin","styleUrlsPlugin","svgrPlugin","virtualModulesPlugin","name","plugin","bundlerConfig","omitDefault","includes","flatMap","getBundleType","getProcessEnv","isProduction","build","isWebComponent","package","config","cacheDir","customLogger","createFilteringLogger","server","host","port","mode","bundleConstants","production","development","configFile","oxc","legalComments","base","getCdnPath","css","createCssConfig","cssCodeSplit","sourcemap","rolldownOptions","output","assetFileNames","codeSplitting","getCodeSplitting","plugins","chainSourceMapsPlugin","define","global","defineExposedDependencies","defineExposedInstanceDependencies","defineWebComponentName","optimizeDeps","include","omitKeys","k","startsWith","length","omit","minify","js","cssMinify","options","codeCoverage"],"mappings":";;;;+BAgFgBA;;;eAAAA;;;sBAvET;uBACc;yBAmBd;gCAEwB;+BACE;iCACD;uCACM;AAEtC,SAASC,gBACL,GAAGC,WAAmD;IAEtD,MAAMC,SAAiC,CAAC;IAExCD,YACKE,MAAM,CAACC,CAAAA,aAAcA,eAAeC,WACpCC,OAAO,CAACF,CAAAA,aACLG,OAAOC,IAAI,CAACJ,YAAYE,OAAO,CAACG,CAAAA;YAC5BP,MAAM,CAAC,CAAC,gBAAgB,EAAEO,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AC3B;IAEA,MAAMgE,YAAWhE,qCAAAA,QAAQoB,aAAa,CAACC,WAAW,cAAjCrB,yDAAAA,mCAAmCR,MAAM,CAACyE,CAAAA,IAAK,CAACA,EAAEC,UAAU,CAAC;IAC9E,IAAIF,qBAAAA,+BAAAA,SAAUG,MAAM,EAAE;QAClBrC,SAASsC,IAAAA,WAAI,EAAC;YAAE,GAAGtC,MAAM;QAAC,GAAGkC;IACjC;IAEA,IAAIhE,QAAQoB,aAAa,CAACiD,MAAM,CAACC,EAAE,KAAK5E,WAAW;QAC/CoC,OAAOH,KAAK,GAAG;YAAE,GAAGG,OAAOH,KAAK;YAAE0C,QAAQ,CAAC,CAACrE,QAAQoB,aAAa,CAACiD,MAAM,CAACC,EAAE;QAAC;IAChF;IACA,IAAItE,QAAQoB,aAAa,CAACiD,MAAM,CAACvB,GAAG,KAAKpD,WAAW;QAChDoC,OAAOH,KAAK,GAAG;YAAE,GAAGG,OAAOH,KAAK;YAAE4C,WAAW,CAAC,CAACvE,QAAQoB,aAAa,CAACiD,MAAM,CAACvB,GAAG;QAAC;IACpF;IAEA,iFAAiF;IACjF,IAAI9C,QAAQwE,OAAO,CAACC,YAAY,EAAE;QAC9B3C,OAAOH,KAAK,GAAG;YAAE,GAAGG,OAAOH,KAAK;YAAE0C,QAAQ;QAAM;IACpD;IAEA,OAAOvC;AACX"}
1
+ {"version":3,"sources":["../../../src/vite/config/base-config.ts"],"sourcesContent":["import type { InlineConfig, Plugin } from 'vite';\nimport {\n bundleConstants,\n defineExposedDependencies,\n defineExposedInstanceDependencies,\n defineWebComponentName,\n getBundleType,\n getCdnPath,\n getProcessEnv,\n} from '../../core';\nimport { omit } from '../../utils';\nimport {\n bundleStatPlugin,\n chainSourceMapsPlugin,\n cleanPlugin,\n cssInjectorPlugin,\n designSystemGuardPlugin,\n devServerRoutingPlugin,\n externalsPlugin,\n htmlPlugin,\n ignoreModulesPlugin,\n istanbulPlugin,\n magicCommentsPlugin,\n metadataPlugin,\n momentLocalesPlugin,\n reactRefreshPlugin,\n styleUrlsPlugin,\n svgrPlugin,\n virtualModulesPlugin,\n} from '../plugins';\nimport { ViteBuildContext } from '../types';\nimport { assetFileNames } from './asset-file-names';\nimport { getCodeSplitting } from './code-splitting';\nimport { createCssConfig } from './create-css-config';\nimport { createFilteringLogger } from './create-filtering-logger';\nimport { createResolveConfig } from './create-resolve-config';\n\nfunction importMetaRemap(\n ...definitions: (Record<string, string> | undefined)[]\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n definitions\n .filter(definition => definition !== undefined)\n .forEach(definition =>\n Object.keys(definition).forEach(item => {\n result[`import.meta.env.${item}`] = definition[item];\n })\n );\n\n return result;\n}\n\nfunction createPlugins(context: ViteBuildContext) {\n const entries: [string, Plugin[] | Plugin | Promise<Plugin> | undefined][] = [\n ['reactRefresh', reactRefreshPlugin(context)],\n ['bundleStat', bundleStatPlugin(context)],\n ['clean', cleanPlugin(context)],\n ['cssInjector', cssInjectorPlugin(context)],\n ['designSystemGuard', designSystemGuardPlugin(context)],\n ['devServerRouting', devServerRoutingPlugin(context)],\n ['externals', externalsPlugin(context)],\n ['html', htmlPlugin(context)],\n ['ignoreModules', ignoreModulesPlugin(context)],\n ['istanbul', istanbulPlugin(context)],\n ['magicComments', magicCommentsPlugin(context)],\n ['metadata', metadataPlugin(context)],\n ['momentLocales', momentLocalesPlugin(context)],\n ['styleUrls', styleUrlsPlugin(context)],\n ['svgr', svgrPlugin(context)],\n ['virtualModules', virtualModulesPlugin(context)],\n ];\n\n return entries\n .filter(\n ([name, plugin]) =>\n plugin && !context.bundlerConfig.omitDefault?.includes(`plugins.${name}`)\n )\n .flatMap(([, plugin]) => plugin);\n}\n\nexport function createBaseConfig(context: ViteBuildContext): InlineConfig {\n const optimizedStartupDependencies = ['@servicetitan/startup-utils', 'react-refresh/runtime'];\n const { isProduction } = context.build;\n const { isWebComponent } = context.package;\n\n let config: InlineConfig = {\n cacheDir: `node_modules/.vite/${getBundleType(context) ?? 'host'}`,\n customLogger: createFilteringLogger(),\n server: {\n // Windows machines can fail to connect to \"localhost\"; bind to a fixed address instead.\n host: '127.0.0.1',\n port: context.bundlerConfig.port ?? (isWebComponent ? 8888 : 8080),\n },\n mode: isProduction ? bundleConstants.mode.production : bundleConstants.mode.development,\n configFile: false,\n oxc: { legalComments: 'none' },\n base: getCdnPath(context) || './', // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing\n css: createCssConfig(isProduction),\n build: {\n /*\n * MFEs render inside shadow DOM — lazy CSS chunks would inject into document.head,\n * leaking styles into the host. Bundling all CSS into one file avoids this.\n */\n cssCodeSplit: !isWebComponent,\n sourcemap: true,\n rolldownOptions: {\n output: { assetFileNames, codeSplitting: getCodeSplitting(context) },\n plugins: [chainSourceMapsPlugin()],\n },\n },\n define: {\n /*\n * Some dependencies assume Node's `global` exists (webpack polyfills this\n * automatically for browser targets; Vite does not).\n */\n global: 'globalThis',\n ...importMetaRemap(\n defineExposedDependencies(context),\n defineExposedInstanceDependencies(context),\n defineWebComponentName(context)\n ),\n ...(getProcessEnv(context) ?? {}),\n },\n resolve: createResolveConfig(context, optimizedStartupDependencies),\n optimizeDeps: {\n include: [\n ...optimizedStartupDependencies,\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n ],\n /*\n * Top-level plugins don't run during dependency pre-bundling, so\n * register ignoreModulesPlugin again here. Without this, missing\n * optional peer dependencies inside pre-bundled packages throw at\n * runtime instead of resolving to an empty module.\n */\n rolldownOptions: {\n plugins: [ignoreModulesPlugin(context)],\n },\n },\n plugins: createPlugins(context),\n };\n\n const omitKeys = context.bundlerConfig.omitDefault?.filter(k => !k.startsWith('plugins.'));\n if (omitKeys?.length) {\n config = omit({ ...config }, omitKeys);\n }\n\n if (context.bundlerConfig.minify.js !== undefined) {\n config.build = { ...config.build, minify: !!context.bundlerConfig.minify.js };\n }\n if (context.bundlerConfig.minify.css !== undefined) {\n config.build = { ...config.build, cssMinify: !!context.bundlerConfig.minify.css };\n }\n\n // Minified output can't be mapped back to source, so skip it when instrumenting.\n if (context.options.codeCoverage) {\n config.build = { ...config.build, minify: false };\n }\n\n return config;\n}\n"],"names":["createBaseConfig","importMetaRemap","definitions","result","filter","definition","undefined","forEach","Object","keys","item","createPlugins","context","entries","reactRefreshPlugin","bundleStatPlugin","cleanPlugin","cssInjectorPlugin","designSystemGuardPlugin","devServerRoutingPlugin","externalsPlugin","htmlPlugin","ignoreModulesPlugin","istanbulPlugin","magicCommentsPlugin","metadataPlugin","momentLocalesPlugin","styleUrlsPlugin","svgrPlugin","virtualModulesPlugin","name","plugin","bundlerConfig","omitDefault","includes","flatMap","getBundleType","getProcessEnv","optimizedStartupDependencies","isProduction","build","isWebComponent","package","config","cacheDir","customLogger","createFilteringLogger","server","host","port","mode","bundleConstants","production","development","configFile","oxc","legalComments","base","getCdnPath","css","createCssConfig","cssCodeSplit","sourcemap","rolldownOptions","output","assetFileNames","codeSplitting","getCodeSplitting","plugins","chainSourceMapsPlugin","define","global","defineExposedDependencies","defineExposedInstanceDependencies","defineWebComponentName","resolve","createResolveConfig","optimizeDeps","include","omitKeys","k","startsWith","length","omit","minify","js","cssMinify","options","codeCoverage"],"mappings":";;;;+BAiFgBA;;;eAAAA;;;sBAxET;uBACc;yBAmBd;gCAEwB;+BACE;iCACD;uCACM;qCACF;AAEpC,SAASC,gBACL,GAAGC,WAAmD;IAEtD,MAAMC,SAAiC,CAAC;IAExCD,YACKE,MAAM,CAACC,CAAAA,aAAcA,eAAeC,WACpCC,OAAO,CAACF,CAAAA,aACLG,OAAOC,IAAI,CAACJ,YAAYE,OAAO,CAACG,CAAAA;YAC5BP,MAAM,CAAC,CAAC,gBAAgB,EAAEO,MAAM,CAAC,GAAGL,UAAU,CAACK,KAAK;QACxD;IAGR,OAAOP;AACX;AAEA,SAASQ,cAAcC,OAAyB;IAC5C,MAAMC,UAAuE;QACzE;YAAC;YAAgBC,IAAAA,2BAAkB,EAACF;SAAS;QAC7C;YAAC;YAAcG,IAAAA,yBAAgB,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IAAK,CAACA,EAAEC,UAAU,CAAC;IAC9E,IAAIF,qBAAAA,+BAAAA,SAAUG,MAAM,EAAE;QAClBvC,SAASwC,IAAAA,WAAI,EAAC;YAAE,GAAGxC,MAAM;QAAC,GAAGoC;IACjC;IAEA,IAAInE,QAAQoB,aAAa,CAACoD,MAAM,CAACC,EAAE,KAAK/E,WAAW;QAC/CqC,OAAOH,KAAK,GAAG;YAAE,GAAGG,OAAOH,KAAK;YAAE4C,QAAQ,CAAC,CAACxE,QAAQoB,aAAa,CAACoD,MAAM,CAACC,EAAE;QAAC;IAChF;IACA,IAAIzE,QAAQoB,aAAa,CAACoD,MAAM,CAACzB,GAAG,KAAKrD,WAAW;QAChDqC,OAAOH,KAAK,GAAG;YAAE,GAAGG,OAAOH,KAAK;YAAE8C,WAAW,CAAC,CAAC1E,QAAQoB,aAAa,CAACoD,MAAM,CAACzB,GAAG;QAAC;IACpF;IAEA,iFAAiF;IACjF,IAAI/C,QAAQ2E,OAAO,CAACC,YAAY,EAAE;QAC9B7C,OAAOH,KAAK,GAAG;YAAE,GAAGG,OAAOH,KAAK;YAAE4C,QAAQ;QAAM;IACpD;IAEA,OAAOzC;AACX"}
@@ -0,0 +1,6 @@
1
+ import type { InlineConfig } from 'vite';
2
+ import type { ViteBuildContext } from '../types';
3
+ type Result = InlineConfig['resolve'];
4
+ export declare function createResolveConfig(context: ViteBuildContext, specifiers: string[]): Result;
5
+ export {};
6
+ //# sourceMappingURL=create-resolve-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-resolve-config.d.ts","sourceRoot":"","sources":["../../../src/vite/config/create-resolve-config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AAEzC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAEjD,KAAK,MAAM,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAQtC,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,MAAM,CAW3F"}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "createResolveConfig", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return createResolveConfig;
9
+ }
10
+ });
11
+ const _module = require("module");
12
+ const _path = /*#__PURE__*/ _interop_require_default(require("path"));
13
+ const _buildescapedregexp = require("../build-escaped-reg-exp");
14
+ function _interop_require_default(obj) {
15
+ return obj && obj.__esModule ? obj : {
16
+ default: obj
17
+ };
18
+ }
19
+ const startupRequire = (0, _module.createRequire)(__filename);
20
+ function createResolveConfig(context, specifiers) {
21
+ const source = _path.default.resolve(context.package.source);
22
+ const alias = specifiers.filter((specifier)=>!isResolvableFrom(specifier, source)).map((specifier)=>({
23
+ find: (0, _buildescapedregexp.buildEscapedRegExp)(specifier),
24
+ replacement: resolveFromStartup(specifier)
25
+ }));
26
+ return {
27
+ alias
28
+ };
29
+ }
30
+ function isResolvableFrom(specifier, source) {
31
+ try {
32
+ require.resolve(specifier, {
33
+ paths: [
34
+ source
35
+ ]
36
+ });
37
+ return true;
38
+ } catch (unused) {
39
+ return false;
40
+ }
41
+ }
42
+ function resolveFromStartup(specifier) {
43
+ try {
44
+ return startupRequire.resolve(specifier);
45
+ } catch (cause) {
46
+ throw new Error(`[startup] Cannot resolve ${specifier}`, {
47
+ cause
48
+ });
49
+ }
50
+ }
51
+
52
+ //# sourceMappingURL=create-resolve-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/vite/config/create-resolve-config.ts"],"sourcesContent":["import { createRequire } from 'module';\nimport path from 'path';\nimport type { InlineConfig } from 'vite';\nimport { buildEscapedRegExp } from '../build-escaped-reg-exp';\nimport type { ViteBuildContext } from '../types';\n\ntype Result = InlineConfig['resolve'];\n\nconst startupRequire = createRequire(__filename);\n\n/*\n * Returns a resolver that, when normal resolution fails for a specifier,\n * tries resolving from startup's location.\n */\nexport function createResolveConfig(context: ViteBuildContext, specifiers: string[]): Result {\n const source = path.resolve(context.package.source);\n\n const alias = specifiers\n .filter(specifier => !isResolvableFrom(specifier, source))\n .map(specifier => ({\n find: buildEscapedRegExp(specifier),\n replacement: resolveFromStartup(specifier),\n }));\n\n return { alias };\n}\n\nfunction isResolvableFrom(specifier: string, source: string): boolean {\n try {\n require.resolve(specifier, { paths: [source] });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction resolveFromStartup(specifier: string): string {\n try {\n return startupRequire.resolve(specifier);\n } catch (cause) {\n throw new Error(`[startup] Cannot resolve ${specifier}`, { cause });\n }\n}\n"],"names":["createResolveConfig","startupRequire","createRequire","__filename","context","specifiers","source","path","resolve","package","alias","filter","specifier","isResolvableFrom","map","find","buildEscapedRegExp","replacement","resolveFromStartup","require","paths","cause","Error"],"mappings":";;;;+BAcgBA;;;eAAAA;;;wBAdc;6DACb;oCAEkB;;;;;;AAKnC,MAAMC,iBAAiBC,IAAAA,qBAAa,EAACC;AAM9B,SAASH,oBAAoBI,OAAyB,EAAEC,UAAoB;IAC/E,MAAMC,SAASC,aAAI,CAACC,OAAO,CAACJ,QAAQK,OAAO,CAACH,MAAM;IAElD,MAAMI,QAAQL,WACTM,MAAM,CAACC,CAAAA,YAAa,CAACC,iBAAiBD,WAAWN,SACjDQ,GAAG,CAACF,CAAAA,YAAc,CAAA;YACfG,MAAMC,IAAAA,sCAAkB,EAACJ;YACzBK,aAAaC,mBAAmBN;QACpC,CAAA;IAEJ,OAAO;QAAEF;IAAM;AACnB;AAEA,SAASG,iBAAiBD,SAAiB,EAAEN,MAAc;IACvD,IAAI;QACAa,QAAQX,OAAO,CAACI,WAAW;YAAEQ,OAAO;gBAACd;aAAO;QAAC;QAC7C,OAAO;IACX,EAAE,eAAM;QACJ,OAAO;IACX;AACJ;AAEA,SAASY,mBAAmBN,SAAiB;IACzC,IAAI;QACA,OAAOX,eAAeO,OAAO,CAACI;IAClC,EAAE,OAAOS,OAAO;QACZ,MAAM,IAAIC,MAAM,CAAC,yBAAyB,EAAEV,WAAW,EAAE;YAAES;QAAM;IACrE;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"css-injector-plugin.d.ts","sourceRoot":"","sources":["../../../src/vite/plugins/css-injector-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAgB/C,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CA+C3E"}
1
+ {"version":3,"file":"css-injector-plugin.d.ts","sourceRoot":"","sources":["../../../src/vite/plugins/css-injector-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAgB/C,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAoD3E"}
@@ -30,7 +30,11 @@ function cssInjectorPlugin(context) {
30
30
  if (!importPattern.test(transformed) || !transformed.includes(callPattern)) {
31
31
  this.error(`[startup] Failed to transform CSS module — Vite's internal output format may have changed. File: ${id}`);
32
32
  }
33
- transformed = transformed.replace(importPattern, `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components'`).replace(callPattern, `__mfe__Registry.for(${JSON.stringify(name)}).injectSheet(__vite__id, __vite__css)`).replace(/import\.meta\.hot\.prune\(\(\) => __vite__removeStyle\(__vite__id\)\)/, '');
33
+ transformed = transformed.replace(importPattern, /*
34
+ * Leaf module, not the package root: the root reaches anvil2, whose
35
+ * stylesheets are rewritten here, and the cycle leaves the registry
36
+ * undefined.
37
+ */ `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components/css-injector/mfe-style-registry'`).replace(callPattern, `__mfe__Registry.for(${JSON.stringify(name)}).injectSheet(__vite__id, __vite__css)`).replace(/import\.meta\.hot\.prune\(\(\) => __vite__removeStyle\(__vite__id\)\)/, '');
34
38
  return {
35
39
  code: transformed,
36
40
  map: null
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/vite/plugins/css-injector-plugin.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport type { BuildContext } from '../../core';\n\n/*\n * Replaces Vite's default CSS injection (<style> tags in document.head) with\n * MfeStyleRegistry.injectSheet() from @servicetitan/web-components, which\n * creates CSSStyleSheet objects that can be adopted into shadow roots.\n *\n * Works by transforming Vite's CSS module output at enforce:'post'. Vite\n * transforms CSS imports into JS modules that call updateStyle(id, css) from\n * /@vite/client — this plugin replaces that call with injectSheet().\n *\n * HMR works automatically: when a CSS file changes, Vite re-evaluates the\n * module, which re-runs injectSheet(). Existing CSSStyleSheet objects are\n * updated via replaceSync(), so all shadow roots that adopted them see the\n * change immediately.\n */\nexport function cssInjectorPlugin(context: BuildContext): Plugin | undefined {\n const { name, isProduction } = context.build;\n const { isWebComponent } = context.package;\n if (!isWebComponent || isProduction) {\n return;\n }\n\n return {\n name: 'st:mfe-css-injector',\n enforce: 'post',\n transform(code, id) {\n if (!id.endsWith('.css') && !id.endsWith('.less') && !id.endsWith('.scss')) {\n return;\n }\n if (!code.includes('__vite__updateStyle')) {\n return;\n }\n\n let transformed = code;\n\n const importPattern =\n /import \\{ updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle \\} from [^\\n]+/;\n const callPattern = '__vite__updateStyle(__vite__id, __vite__css)';\n\n if (!importPattern.test(transformed) || !transformed.includes(callPattern)) {\n this.error(\n `[startup] Failed to transform CSS module — Vite's internal output format may have changed. File: ${id}`\n );\n }\n\n transformed = transformed\n .replace(\n importPattern,\n `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components'`\n )\n .replace(\n callPattern,\n `__mfe__Registry.for(${JSON.stringify(name)}).injectSheet(__vite__id, __vite__css)`\n )\n .replace(\n /import\\.meta\\.hot\\.prune\\(\\(\\) => __vite__removeStyle\\(__vite__id\\)\\)/,\n ''\n );\n\n return { code: transformed, map: null };\n },\n };\n}\n"],"names":["cssInjectorPlugin","context","name","isProduction","build","isWebComponent","package","enforce","transform","code","id","endsWith","includes","transformed","importPattern","callPattern","test","error","replace","JSON","stringify","map"],"mappings":";;;;+BAiBgBA;;;eAAAA;;;AAAT,SAASA,kBAAkBC,OAAqB;IACnD,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF,QAAQG,KAAK;IAC5C,MAAM,EAAEC,cAAc,EAAE,GAAGJ,QAAQK,OAAO;IAC1C,IAAI,CAACD,kBAAkBF,cAAc;QACjC;IACJ;IAEA,OAAO;QACHD,MAAM;QACNK,SAAS;QACTC,WAAUC,IAAI,EAAEC,EAAE;YACd,IAAI,CAACA,GAAGC,QAAQ,CAAC,WAAW,CAACD,GAAGC,QAAQ,CAAC,YAAY,CAACD,GAAGC,QAAQ,CAAC,UAAU;gBACxE;YACJ;YACA,IAAI,CAACF,KAAKG,QAAQ,CAAC,wBAAwB;gBACvC;YACJ;YAEA,IAAIC,cAAcJ;YAElB,MAAMK,gBACF;YACJ,MAAMC,cAAc;YAEpB,IAAI,CAACD,cAAcE,IAAI,CAACH,gBAAgB,CAACA,YAAYD,QAAQ,CAACG,cAAc;gBACxE,IAAI,CAACE,KAAK,CACN,CAAC,iGAAiG,EAAEP,IAAI;YAEhH;YAEAG,cAAcA,YACTK,OAAO,CACJJ,eACA,CAAC,kFAAkF,CAAC,EAEvFI,OAAO,CACJH,aACA,CAAC,oBAAoB,EAAEI,KAAKC,SAAS,CAAClB,MAAM,sCAAsC,CAAC,EAEtFgB,OAAO,CACJ,yEACA;YAGR,OAAO;gBAAET,MAAMI;gBAAaQ,KAAK;YAAK;QAC1C;IACJ;AACJ"}
1
+ {"version":3,"sources":["../../../src/vite/plugins/css-injector-plugin.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport type { BuildContext } from '../../core';\n\n/*\n * Replaces Vite's default CSS injection (<style> tags in document.head) with\n * MfeStyleRegistry.injectSheet() from @servicetitan/web-components, which\n * creates CSSStyleSheet objects that can be adopted into shadow roots.\n *\n * Works by transforming Vite's CSS module output at enforce:'post'. Vite\n * transforms CSS imports into JS modules that call updateStyle(id, css) from\n * /@vite/client — this plugin replaces that call with injectSheet().\n *\n * HMR works automatically: when a CSS file changes, Vite re-evaluates the\n * module, which re-runs injectSheet(). Existing CSSStyleSheet objects are\n * updated via replaceSync(), so all shadow roots that adopted them see the\n * change immediately.\n */\nexport function cssInjectorPlugin(context: BuildContext): Plugin | undefined {\n const { name, isProduction } = context.build;\n const { isWebComponent } = context.package;\n if (!isWebComponent || isProduction) {\n return;\n }\n\n return {\n name: 'st:mfe-css-injector',\n enforce: 'post',\n transform(code, id) {\n if (!id.endsWith('.css') && !id.endsWith('.less') && !id.endsWith('.scss')) {\n return;\n }\n if (!code.includes('__vite__updateStyle')) {\n return;\n }\n\n let transformed = code;\n\n const importPattern =\n /import \\{ updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle \\} from [^\\n]+/;\n const callPattern = '__vite__updateStyle(__vite__id, __vite__css)';\n\n if (!importPattern.test(transformed) || !transformed.includes(callPattern)) {\n this.error(\n `[startup] Failed to transform CSS module — Vite's internal output format may have changed. File: ${id}`\n );\n }\n\n transformed = transformed\n .replace(\n importPattern,\n /*\n * Leaf module, not the package root: the root reaches anvil2, whose\n * stylesheets are rewritten here, and the cycle leaves the registry\n * undefined.\n */\n `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components/css-injector/mfe-style-registry'`\n )\n .replace(\n callPattern,\n `__mfe__Registry.for(${JSON.stringify(name)}).injectSheet(__vite__id, __vite__css)`\n )\n .replace(\n /import\\.meta\\.hot\\.prune\\(\\(\\) => __vite__removeStyle\\(__vite__id\\)\\)/,\n ''\n );\n\n return { code: transformed, map: null };\n },\n };\n}\n"],"names":["cssInjectorPlugin","context","name","isProduction","build","isWebComponent","package","enforce","transform","code","id","endsWith","includes","transformed","importPattern","callPattern","test","error","replace","JSON","stringify","map"],"mappings":";;;;+BAiBgBA;;;eAAAA;;;AAAT,SAASA,kBAAkBC,OAAqB;IACnD,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF,QAAQG,KAAK;IAC5C,MAAM,EAAEC,cAAc,EAAE,GAAGJ,QAAQK,OAAO;IAC1C,IAAI,CAACD,kBAAkBF,cAAc;QACjC;IACJ;IAEA,OAAO;QACHD,MAAM;QACNK,SAAS;QACTC,WAAUC,IAAI,EAAEC,EAAE;YACd,IAAI,CAACA,GAAGC,QAAQ,CAAC,WAAW,CAACD,GAAGC,QAAQ,CAAC,YAAY,CAACD,GAAGC,QAAQ,CAAC,UAAU;gBACxE;YACJ;YACA,IAAI,CAACF,KAAKG,QAAQ,CAAC,wBAAwB;gBACvC;YACJ;YAEA,IAAIC,cAAcJ;YAElB,MAAMK,gBACF;YACJ,MAAMC,cAAc;YAEpB,IAAI,CAACD,cAAcE,IAAI,CAACH,gBAAgB,CAACA,YAAYD,QAAQ,CAACG,cAAc;gBACxE,IAAI,CAACE,KAAK,CACN,CAAC,iGAAiG,EAAEP,IAAI;YAEhH;YAEAG,cAAcA,YACTK,OAAO,CACJJ,eACA;;;;qBAIC,GACD,CAAC,kHAAkH,CAAC,EAEvHI,OAAO,CACJH,aACA,CAAC,oBAAoB,EAAEI,KAAKC,SAAS,CAAClB,MAAM,sCAAsC,CAAC,EAEtFgB,OAAO,CACJ,yEACA;YAGR,OAAO;gBAAET,MAAMI;gBAAaQ,KAAK;YAAK;QAC1C;IACJ;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"externals-plugin.d.ts","sourceRoot":"","sources":["../../../src/vite/plugins/externals-plugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,YAAY,EAAgB,MAAM,YAAY,CAAC;AAoCxD,wBAAgB,eAAe,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAkDzE"}
1
+ {"version":3,"file":"externals-plugin.d.ts","sourceRoot":"","sources":["../../../src/vite/plugins/externals-plugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,YAAY,EAAgB,MAAM,YAAY,CAAC;AAiCxD,wBAAgB,eAAe,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAkDzE"}
@@ -11,12 +11,12 @@ Object.defineProperty(exports, "externalsPlugin", {
11
11
  const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
12
12
  const _path = /*#__PURE__*/ _interop_require_default(require("path"));
13
13
  const _core = require("../../core");
14
+ const _buildescapedregexp = require("../build-escaped-reg-exp");
14
15
  function _interop_require_default(obj) {
15
16
  return obj && obj.__esModule ? obj : {
16
17
  default: obj
17
18
  };
18
19
  }
19
- /* Dots are the only valid regex-special character in package names */ const buildEscapedRegExp = (dependency)=>new RegExp(`^${dependency.replace(/\./g, '\\.')}$`);
20
20
  function externalsPlugin(context) {
21
21
  const entries = (0, _core.getExternals)(context);
22
22
  if (!entries) {
@@ -42,7 +42,7 @@ function externalsPlugin(context) {
42
42
  config: isProduction ? undefined : ()=>({
43
43
  resolve: {
44
44
  alias: Object.keys(entries).map((dep)=>({
45
- find: buildEscapedRegExp(dep),
45
+ find: (0, _buildescapedregexp.buildEscapedRegExp)(dep),
46
46
  replacement: _path.default.join(proxyNodeModules, dep)
47
47
  }))
48
48
  },
@@ -52,7 +52,7 @@ function externalsPlugin(context) {
52
52
  }),
53
53
  resolveId: isProduction ? {
54
54
  filter: {
55
- id: Object.keys(entries).map(buildEscapedRegExp)
55
+ id: Object.keys(entries).map(_buildescapedregexp.buildEscapedRegExp)
56
56
  },
57
57
  handler (source) {
58
58
  if (source in entries) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/vite/plugins/externals-plugin.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport type { Plugin } from 'vite';\nimport { BuildContext, getExternals } from '../../core';\n\n/* Dots are the only valid regex-special character in package names */\nconst buildEscapedRegExp = (dependency: string) =>\n new RegExp(`^${dependency.replace(/\\./g, '\\\\.')}$`);\n\n/*\n * Externalizes shared dependencies by redirecting imports to CJS proxy modules\n * that read from the host's global shared deps registry at runtime.\n *\n * Each shared dep gets a fake package on disk (node_modules/.startup/externals/)\n * with `module.exports = SharedDependencies.Foo['scope']`.\n *\n * Three mechanisms work together, each handling a different mode:\n *\n * - resolve.alias (dev) — exact-match regex redirects `react` to the proxy package.\n * Subpath imports (react/jsx-runtime) are NOT matched and resolve normally.\n *\n * - optimizeDeps.include (dev) — forces Vite to pre-bundle the proxy packages.\n * This triggers Vite's CJS-to-ESM interop: the pre-bundled output has `export default`,\n * and Vite's import-analysis plugin rewrites consumers' named imports to property access\n * on the default export (e.g. `import { useState } from 'react'` becomes\n * `const useState = __default[\"useState\"]`). Without optimizeDeps, the raw CJS proxy\n * would be served to the browser and fail on named imports.\n *\n * - resolveId (prod) — resolve.alias doesn't run during Rolldown bundling, so resolveId\n * with enforce:'pre' intercepts shared dep imports before Vite's default resolver.\n * Rolldown handles CJS-to-ESM interop natively via __commonJSMin/__toESM helpers.\n * Only exact matches — subpath imports must NOT be redirected because they export\n * different things than the barrel.\n *\n * The disk-based proxy + optimizeDeps complexity exists because Vite's dev server serves\n * modules as native ESM without bundling — CJS virtual modules can't be served to the browser.\n * When Vite's \"full bundle\" dev mode ships (Rolldown bundles in dev, like prod), this can be\n * simplified to a single resolveId + load with a virtual CJS module for both modes (see 9ffd1815).\n */\nexport function externalsPlugin(context: BuildContext): Plugin | undefined {\n const entries = getExternals(context);\n if (!entries) {\n return;\n }\n\n const proxyModulesDir = path.resolve('node_modules', '.startup', 'externals');\n for (const [dep, proxy] of Object.entries(entries)) {\n const pkgDir = path.join(proxyModulesDir, 'node_modules', dep);\n fs.mkdirSync(pkgDir, { recursive: true });\n fs.writeFileSync(path.join(pkgDir, 'index.cjs'), `module.exports = ${proxy};`);\n fs.writeFileSync(\n path.join(pkgDir, 'package.json'),\n JSON.stringify({ name: dep, main: './index.cjs' })\n );\n }\n\n const proxyNodeModules = path.join(proxyModulesDir, 'node_modules');\n\n const { isProduction } = context.build;\n\n return {\n name: 'st:externals',\n enforce: 'pre',\n config: isProduction\n ? undefined\n : () => ({\n resolve: {\n alias: Object.keys(entries).map(dep => ({\n find: buildEscapedRegExp(dep),\n replacement: path.join(proxyNodeModules, dep),\n })),\n },\n optimizeDeps: {\n include: Object.keys(entries),\n },\n }),\n resolveId: isProduction\n ? {\n filter: {\n id: Object.keys(entries).map(buildEscapedRegExp),\n },\n handler(source: string) {\n if (source in entries) {\n return path.join(proxyNodeModules, source, 'index.cjs');\n }\n },\n }\n : undefined,\n };\n}\n"],"names":["externalsPlugin","buildEscapedRegExp","dependency","RegExp","replace","context","entries","getExternals","proxyModulesDir","path","resolve","dep","proxy","Object","pkgDir","join","fs","mkdirSync","recursive","writeFileSync","JSON","stringify","name","main","proxyNodeModules","isProduction","build","enforce","config","undefined","alias","keys","map","find","replacement","optimizeDeps","include","resolveId","filter","id","handler","source"],"mappings":";;;;+BAuCgBA;;;eAAAA;;;2DAvCD;6DACE;sBAE0B;;;;;;AAE3C,oEAAoE,GACpE,MAAMC,qBAAqB,CAACC,aACxB,IAAIC,OAAO,CAAC,CAAC,EAAED,WAAWE,OAAO,CAAC,OAAO,OAAO,CAAC,CAAC;AAgC/C,SAASJ,gBAAgBK,OAAqB;IACjD,MAAMC,UAAUC,IAAAA,kBAAY,EAACF;IAC7B,IAAI,CAACC,SAAS;QACV;IACJ;IAEA,MAAME,kBAAkBC,aAAI,CAACC,OAAO,CAAC,gBAAgB,YAAY;IACjE,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOP,OAAO,CAACA,SAAU;QAChD,MAAMQ,SAASL,aAAI,CAACM,IAAI,CAACP,iBAAiB,gBAAgBG;QAC1DK,WAAE,CAACC,SAAS,CAACH,QAAQ;YAAEI,WAAW;QAAK;QACvCF,WAAE,CAACG,aAAa,CAACV,aAAI,CAACM,IAAI,CAACD,QAAQ,cAAc,CAAC,iBAAiB,EAAEF,MAAM,CAAC,CAAC;QAC7EI,WAAE,CAACG,aAAa,CACZV,aAAI,CAACM,IAAI,CAACD,QAAQ,iBAClBM,KAAKC,SAAS,CAAC;YAAEC,MAAMX;YAAKY,MAAM;QAAc;IAExD;IAEA,MAAMC,mBAAmBf,aAAI,CAACM,IAAI,CAACP,iBAAiB;IAEpD,MAAM,EAAEiB,YAAY,EAAE,GAAGpB,QAAQqB,KAAK;IAEtC,OAAO;QACHJ,MAAM;QACNK,SAAS;QACTC,QAAQH,eACFI,YACA,IAAO,CAAA;gBACHnB,SAAS;oBACLoB,OAAOjB,OAAOkB,IAAI,CAACzB,SAAS0B,GAAG,CAACrB,CAAAA,MAAQ,CAAA;4BACpCsB,MAAMhC,mBAAmBU;4BACzBuB,aAAazB,aAAI,CAACM,IAAI,CAACS,kBAAkBb;wBAC7C,CAAA;gBACJ;gBACAwB,cAAc;oBACVC,SAASvB,OAAOkB,IAAI,CAACzB;gBACzB;YACJ,CAAA;QACN+B,WAAWZ,eACL;YACIa,QAAQ;gBACJC,IAAI1B,OAAOkB,IAAI,CAACzB,SAAS0B,GAAG,CAAC/B;YACjC;YACAuC,SAAQC,MAAc;gBAClB,IAAIA,UAAUnC,SAAS;oBACnB,OAAOG,aAAI,CAACM,IAAI,CAACS,kBAAkBiB,QAAQ;gBAC/C;YACJ;QACJ,IACAZ;IACV;AACJ"}
1
+ {"version":3,"sources":["../../../src/vite/plugins/externals-plugin.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport type { Plugin } from 'vite';\nimport { BuildContext, getExternals } from '../../core';\nimport { buildEscapedRegExp } from '../build-escaped-reg-exp';\n\n/*\n * Externalizes shared dependencies by redirecting imports to CJS proxy modules\n * that read from the host's global shared deps registry at runtime.\n *\n * Each shared dep gets a fake package on disk (node_modules/.startup/externals/)\n * with `module.exports = SharedDependencies.Foo['scope']`.\n *\n * Three mechanisms work together, each handling a different mode:\n *\n * - resolve.alias (dev) — exact-match regex redirects `react` to the proxy package.\n * Subpath imports (react/jsx-runtime) are NOT matched and resolve normally.\n *\n * - optimizeDeps.include (dev) — forces Vite to pre-bundle the proxy packages.\n * This triggers Vite's CJS-to-ESM interop: the pre-bundled output has `export default`,\n * and Vite's import-analysis plugin rewrites consumers' named imports to property access\n * on the default export (e.g. `import { useState } from 'react'` becomes\n * `const useState = __default[\"useState\"]`). Without optimizeDeps, the raw CJS proxy\n * would be served to the browser and fail on named imports.\n *\n * - resolveId (prod) — resolve.alias doesn't run during Rolldown bundling, so resolveId\n * with enforce:'pre' intercepts shared dep imports before Vite's default resolver.\n * Rolldown handles CJS-to-ESM interop natively via __commonJSMin/__toESM helpers.\n * Only exact matches — subpath imports must NOT be redirected because they export\n * different things than the barrel.\n *\n * The disk-based proxy + optimizeDeps complexity exists because Vite's dev server serves\n * modules as native ESM without bundling — CJS virtual modules can't be served to the browser.\n * When Vite's \"full bundle\" dev mode ships (Rolldown bundles in dev, like prod), this can be\n * simplified to a single resolveId + load with a virtual CJS module for both modes (see 9ffd1815).\n */\nexport function externalsPlugin(context: BuildContext): Plugin | undefined {\n const entries = getExternals(context);\n if (!entries) {\n return;\n }\n\n const proxyModulesDir = path.resolve('node_modules', '.startup', 'externals');\n for (const [dep, proxy] of Object.entries(entries)) {\n const pkgDir = path.join(proxyModulesDir, 'node_modules', dep);\n fs.mkdirSync(pkgDir, { recursive: true });\n fs.writeFileSync(path.join(pkgDir, 'index.cjs'), `module.exports = ${proxy};`);\n fs.writeFileSync(\n path.join(pkgDir, 'package.json'),\n JSON.stringify({ name: dep, main: './index.cjs' })\n );\n }\n\n const proxyNodeModules = path.join(proxyModulesDir, 'node_modules');\n\n const { isProduction } = context.build;\n\n return {\n name: 'st:externals',\n enforce: 'pre',\n config: isProduction\n ? undefined\n : () => ({\n resolve: {\n alias: Object.keys(entries).map(dep => ({\n find: buildEscapedRegExp(dep),\n replacement: path.join(proxyNodeModules, dep),\n })),\n },\n optimizeDeps: {\n include: Object.keys(entries),\n },\n }),\n resolveId: isProduction\n ? {\n filter: {\n id: Object.keys(entries).map(buildEscapedRegExp),\n },\n handler(source: string) {\n if (source in entries) {\n return path.join(proxyNodeModules, source, 'index.cjs');\n }\n },\n }\n : undefined,\n };\n}\n"],"names":["externalsPlugin","context","entries","getExternals","proxyModulesDir","path","resolve","dep","proxy","Object","pkgDir","join","fs","mkdirSync","recursive","writeFileSync","JSON","stringify","name","main","proxyNodeModules","isProduction","build","enforce","config","undefined","alias","keys","map","find","buildEscapedRegExp","replacement","optimizeDeps","include","resolveId","filter","id","handler","source"],"mappings":";;;;+BAoCgBA;;;eAAAA;;;2DApCD;6DACE;sBAE0B;oCACR;;;;;;AAgC5B,SAASA,gBAAgBC,OAAqB;IACjD,MAAMC,UAAUC,IAAAA,kBAAY,EAACF;IAC7B,IAAI,CAACC,SAAS;QACV;IACJ;IAEA,MAAME,kBAAkBC,aAAI,CAACC,OAAO,CAAC,gBAAgB,YAAY;IACjE,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOP,OAAO,CAACA,SAAU;QAChD,MAAMQ,SAASL,aAAI,CAACM,IAAI,CAACP,iBAAiB,gBAAgBG;QAC1DK,WAAE,CAACC,SAAS,CAACH,QAAQ;YAAEI,WAAW;QAAK;QACvCF,WAAE,CAACG,aAAa,CAACV,aAAI,CAACM,IAAI,CAACD,QAAQ,cAAc,CAAC,iBAAiB,EAAEF,MAAM,CAAC,CAAC;QAC7EI,WAAE,CAACG,aAAa,CACZV,aAAI,CAACM,IAAI,CAACD,QAAQ,iBAClBM,KAAKC,SAAS,CAAC;YAAEC,MAAMX;YAAKY,MAAM;QAAc;IAExD;IAEA,MAAMC,mBAAmBf,aAAI,CAACM,IAAI,CAACP,iBAAiB;IAEpD,MAAM,EAAEiB,YAAY,EAAE,GAAGpB,QAAQqB,KAAK;IAEtC,OAAO;QACHJ,MAAM;QACNK,SAAS;QACTC,QAAQH,eACFI,YACA,IAAO,CAAA;gBACHnB,SAAS;oBACLoB,OAAOjB,OAAOkB,IAAI,CAACzB,SAAS0B,GAAG,CAACrB,CAAAA,MAAQ,CAAA;4BACpCsB,MAAMC,IAAAA,sCAAkB,EAACvB;4BACzBwB,aAAa1B,aAAI,CAACM,IAAI,CAACS,kBAAkBb;wBAC7C,CAAA;gBACJ;gBACAyB,cAAc;oBACVC,SAASxB,OAAOkB,IAAI,CAACzB;gBACzB;YACJ,CAAA;QACNgC,WAAWb,eACL;YACIc,QAAQ;gBACJC,IAAI3B,OAAOkB,IAAI,CAACzB,SAAS0B,GAAG,CAACE,sCAAkB;YACnD;YACAO,SAAQC,MAAc;gBAClB,IAAIA,UAAUpC,SAAS;oBACnB,OAAOG,aAAI,CAACM,IAAI,CAACS,kBAAkBkB,QAAQ;gBAC/C;YACJ;QACJ,IACAb;IACV;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@servicetitan/startup",
3
- "version": "39.0.1",
3
+ "version": "39.1.0",
4
4
  "description": "CLI to create multi-package Lerna projects with TypeScript and React",
5
5
  "homepage": "https://docs.st.dev/docs/frontend/uikit/startup",
6
6
  "repository": {
@@ -103,10 +103,10 @@
103
103
  "@jest/core": "~30.4.2",
104
104
  "@jest/types": "~30.4.1",
105
105
  "@jsdevtools/coverage-istanbul-loader": "^3.0.5",
106
- "@servicetitan/eslint-config": "39.0.1",
107
- "@servicetitan/install": "39.0.1",
108
- "@servicetitan/startup-utils": "39.0.1",
109
- "@servicetitan/stylelint-config": "39.0.1",
106
+ "@servicetitan/eslint-config": "39.1.0",
107
+ "@servicetitan/install": "39.1.0",
108
+ "@servicetitan/startup-utils": "39.1.0",
109
+ "@servicetitan/stylelint-config": "39.1.0",
110
110
  "@svgr/webpack": "^8.1.0",
111
111
  "@swc/cli": "^0.8.1",
112
112
  "@swc/core": "1.15.46",
@@ -203,5 +203,5 @@
203
203
  "cli": {
204
204
  "webpack": false
205
205
  },
206
- "gitHead": "6e852d0d87277df097ee9fb38b096dae3fb6d68e"
206
+ "gitHead": "a2471578a506e8c40e90956a5c70cc1638bbe9c1"
207
207
  }
@@ -0,0 +1,25 @@
1
+ import { buildEscapedRegExp } from '../build-escaped-reg-exp';
2
+
3
+ describe('buildEscapedRegExp', () => {
4
+ test.each(['react', '@servicetitan/startup-utils', 'react-refresh/runtime'])(
5
+ 'matches %s exactly',
6
+ specifier => {
7
+ expect(buildEscapedRegExp(specifier).test(specifier)).toBe(true);
8
+ }
9
+ );
10
+
11
+ test.each([
12
+ ['lodash.throttle', 'lodashxthrottle'],
13
+ ['lodash.throttle', 'lodash.throttle/extra'],
14
+ ['react', 'react-dom'],
15
+ ['react', 'preact'],
16
+ ])('built from %s does not match %s', (specifier, other) => {
17
+ expect(buildEscapedRegExp(specifier).test(other)).toBe(false);
18
+ });
19
+
20
+ /* Unescaped, a backslash would turn the next character into an escape sequence. */
21
+ test('escapes backslashes rather than emitting them raw', () => {
22
+ expect(buildEscapedRegExp('we\\d').test('we\\d')).toBe(true);
23
+ expect(buildEscapedRegExp('we\\d').test('we5')).toBe(false);
24
+ });
25
+ });
@@ -0,0 +1,6 @@
1
+ /*
2
+ * Dots are the only regex-special character valid in a package name; the
3
+ * backslash is escaped because it is the escape character itself.
4
+ */
5
+ export const buildEscapedRegExp = (specifier: string) =>
6
+ new RegExp(`^${specifier.replace(/[\\.]/g, '\\$&')}$`);
@@ -102,7 +102,7 @@ describe(createBaseConfig.name, () => {
102
102
  context = {
103
103
  build: { isProduction: false },
104
104
  options: {},
105
- package: { isWebComponent: false, destination: 'dist/bundle/full' },
105
+ package: { isWebComponent: false, destination: 'dist/bundle/full', source: 'src' },
106
106
  bundlerConfig: {
107
107
  omitDefault: [],
108
108
  minify: {},
@@ -0,0 +1,85 @@
1
+ import { createRequire } from 'module';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { buildEscapedRegExp } from '../../build-escaped-reg-exp';
6
+ import { ViteBuildContext } from '../../types';
7
+ import { createResolveConfig } from '../create-resolve-config';
8
+
9
+ jest.mock('module', () => ({
10
+ ...jest.requireActual('module'),
11
+ createRequire: jest.fn(() => ({ resolve: jest.fn() })),
12
+ }));
13
+
14
+ describe(`[startup] ${createResolveConfig.name}`, () => {
15
+ let startupRequire: { resolve: (specifier: string) => string };
16
+ let context: Partial<ViteBuildContext>;
17
+ let specifiers: string[];
18
+
19
+ beforeAll(() => {
20
+ startupRequire = jest.mocked(createRequire).mock.results[0].value;
21
+ });
22
+
23
+ beforeEach(() => {
24
+ jest.clearAllMocks();
25
+ jest.mocked(startupRequire.resolve).mockImplementation(() => {
26
+ throw new Error('Module not found');
27
+ });
28
+ const source = fs.mkdtempSync(path.join(os.tmpdir(), 'create-resolve-config-'));
29
+ context = { package: { source } as any };
30
+ specifiers = ['a', '@b/c'];
31
+ });
32
+
33
+ afterEach(() => fs.rmSync(context.package!.source, { recursive: true, force: true }));
34
+
35
+ function mockNodeModules(root: string, modules: string[]) {
36
+ modules.forEach(name => {
37
+ const dir = path.join(root, 'node_modules', ...name.split('/'));
38
+ fs.mkdirSync(dir, { recursive: true });
39
+ fs.writeFileSync(path.join(dir, 'index.js'), '');
40
+ });
41
+ }
42
+
43
+ const subject = () =>
44
+ createResolveConfig(context as any, specifiers) as {
45
+ alias: { find: RegExp; replacement: string }[];
46
+ };
47
+
48
+ test('throws error', () => {
49
+ expect(() => subject()).toThrow(/cannot resolve/i);
50
+ });
51
+
52
+ describe('when specifier is resolvable', () => {
53
+ beforeEach(() => mockNodeModules(context.package!.source, specifiers));
54
+
55
+ test('does nothing', () => {
56
+ expect(subject().alias).toEqual([]);
57
+ });
58
+ });
59
+
60
+ describe('when specifier is resolvable from startup', () => {
61
+ beforeEach(() => {
62
+ jest.mocked(startupRequire.resolve).mockImplementation(
63
+ (specifier: string) => `startup/${specifier}`
64
+ );
65
+ });
66
+
67
+ test('emits alias', () => {
68
+ const { alias } = subject();
69
+
70
+ specifiers.forEach(specifier => {
71
+ expect(alias.find(({ find }) => find.test(specifier))?.replacement).toEqual(
72
+ `startup/${specifier}`
73
+ );
74
+ });
75
+ });
76
+
77
+ test('alias matches whole specifier', () => {
78
+ const { alias } = subject();
79
+
80
+ specifiers.forEach((specifier, i) =>
81
+ expect(alias[i].find).toEqual(buildEscapedRegExp(specifier))
82
+ );
83
+ });
84
+ });
85
+ });
@@ -33,6 +33,7 @@ import { assetFileNames } from './asset-file-names';
33
33
  import { getCodeSplitting } from './code-splitting';
34
34
  import { createCssConfig } from './create-css-config';
35
35
  import { createFilteringLogger } from './create-filtering-logger';
36
+ import { createResolveConfig } from './create-resolve-config';
36
37
 
37
38
  function importMetaRemap(
38
39
  ...definitions: (Record<string, string> | undefined)[]
@@ -79,6 +80,7 @@ function createPlugins(context: ViteBuildContext) {
79
80
  }
80
81
 
81
82
  export function createBaseConfig(context: ViteBuildContext): InlineConfig {
83
+ const optimizedStartupDependencies = ['@servicetitan/startup-utils', 'react-refresh/runtime'];
82
84
  const { isProduction } = context.build;
83
85
  const { isWebComponent } = context.package;
84
86
 
@@ -120,10 +122,10 @@ export function createBaseConfig(context: ViteBuildContext): InlineConfig {
120
122
  ),
121
123
  ...(getProcessEnv(context) ?? {}),
122
124
  },
125
+ resolve: createResolveConfig(context, optimizedStartupDependencies),
123
126
  optimizeDeps: {
124
127
  include: [
125
- '@servicetitan/startup-utils',
126
- 'react-refresh/runtime',
128
+ ...optimizedStartupDependencies,
127
129
  'react/jsx-runtime',
128
130
  'react/jsx-dev-runtime',
129
131
  ],
@@ -0,0 +1,43 @@
1
+ import { createRequire } from 'module';
2
+ import path from 'path';
3
+ import type { InlineConfig } from 'vite';
4
+ import { buildEscapedRegExp } from '../build-escaped-reg-exp';
5
+ import type { ViteBuildContext } from '../types';
6
+
7
+ type Result = InlineConfig['resolve'];
8
+
9
+ const startupRequire = createRequire(__filename);
10
+
11
+ /*
12
+ * Returns a resolver that, when normal resolution fails for a specifier,
13
+ * tries resolving from startup's location.
14
+ */
15
+ export function createResolveConfig(context: ViteBuildContext, specifiers: string[]): Result {
16
+ const source = path.resolve(context.package.source);
17
+
18
+ const alias = specifiers
19
+ .filter(specifier => !isResolvableFrom(specifier, source))
20
+ .map(specifier => ({
21
+ find: buildEscapedRegExp(specifier),
22
+ replacement: resolveFromStartup(specifier),
23
+ }));
24
+
25
+ return { alias };
26
+ }
27
+
28
+ function isResolvableFrom(specifier: string, source: string): boolean {
29
+ try {
30
+ require.resolve(specifier, { paths: [source] });
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ function resolveFromStartup(specifier: string): string {
38
+ try {
39
+ return startupRequire.resolve(specifier);
40
+ } catch (cause) {
41
+ throw new Error(`[startup] Cannot resolve ${specifier}`, { cause });
42
+ }
43
+ }
@@ -64,7 +64,7 @@ describe(cssInjectorPlugin.name, () => {
64
64
  const result = transform(viteCssOutput, viteId);
65
65
 
66
66
  expect(result.code).toContain(
67
- `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components'`
67
+ `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components/css-injector/mfe-style-registry'`
68
68
  );
69
69
  });
70
70
 
@@ -48,7 +48,12 @@ export function cssInjectorPlugin(context: BuildContext): Plugin | undefined {
48
48
  transformed = transformed
49
49
  .replace(
50
50
  importPattern,
51
- `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components'`
51
+ /*
52
+ * Leaf module, not the package root: the root reaches anvil2, whose
53
+ * stylesheets are rewritten here, and the cycle leaves the registry
54
+ * undefined.
55
+ */
56
+ `import { MfeStyleRegistry as __mfe__Registry } from '@servicetitan/web-components/css-injector/mfe-style-registry'`
52
57
  )
53
58
  .replace(
54
59
  callPattern,
@@ -2,10 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import type { Plugin } from 'vite';
4
4
  import { BuildContext, getExternals } from '../../core';
5
-
6
- /* Dots are the only valid regex-special character in package names */
7
- const buildEscapedRegExp = (dependency: string) =>
8
- new RegExp(`^${dependency.replace(/\./g, '\\.')}$`);
5
+ import { buildEscapedRegExp } from '../build-escaped-reg-exp';
9
6
 
10
7
  /*
11
8
  * Externalizes shared dependencies by redirecting imports to CJS proxy modules