@stencil/react-output-target
Version:
React output target for @stencil/core components.
1 lines • 39.6 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../src/utils/string-utils.ts","../src/create-es-modules-components-file.ts","../src/create-stencil-react-components.ts","../src/create-tag-transformer.ts","../src/create-component-wrappers.ts","../src/index.ts"],"sourcesContent":["export const kebabToPascalCase = (str: string) =>\n str\n .toLowerCase()\n .split('-')\n .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))\n .join('');\n\nexport const kebabToCamelCase = (str: string) => str.replace(/-([_a-z])/g, (_, letter) => letter.toUpperCase());\n\nconst slashesToCamelCase = (str: string) => str.replace(/\\/([a-z])/g, (_, letter) => letter.toUpperCase());\n\nexport const eventListenerName = (eventName: string) => {\n const slashesConverted = slashesToCamelCase(eventName);\n return kebabToCamelCase(`on-${slashesConverted}`);\n};\n\n/**\n * Normalizes a type string by removing single-line comments and collapsing whitespace.\n * This is necessary because multiline types with comments would break when collapsed to a single line.\n */\nexport const normalizeTypeString = (type: string) =>\n type\n .replace(/\\/\\/.*$/gm, '') // Remove single-line comments\n .replace(/\\n/g, ' ') // Replace newlines with spaces\n .replace(/\\s{2,}/g, ' ') // Collapse multiple spaces\n .trim();\n","import type { ComponentCompilerMeta } from '@stencil/core/internal';\nimport { kebabToPascalCase } from './utils/string-utils.js';\nimport type { RenderToStringOptions } from './runtime/ssr.js';\n\nexport const createEsModulesComponentsFile = ({\n components,\n componentSuffix = '',\n serializeShadowRoot,\n}: {\n components: ComponentCompilerMeta[];\n componentSuffix?: string;\n serializeShadowRoot?: RenderToStringOptions['serializeShadowRoot'];\n}) => {\n const disableEslint = `/* eslint-disable */`;\n const autogeneratedComment = `/**\n * This file was automatically generated by the Stencil React Output Target.\n * Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.\n */\\n\\n`;\n const source = [autogeneratedComment + disableEslint];\n\n /**\n * Server barrel: emit a single shared `serializeShadowRoot` so consumers\n * don't need to import a per-component file just to get the constant.\n */\n if (componentSuffix) {\n const initializer = serializeShadowRoot\n ? JSON.stringify(serializeShadowRoot)\n : '{ default: \"declarative-shadow-dom\" }';\n\n source.push(\n `import type { SerializeShadowRootOptions } from '@stencil/react-output-target/ssr';`,\n `export const serializeShadowRoot: SerializeShadowRootOptions = ${initializer};`\n );\n }\n\n for (const component of components) {\n const tagName = component.tagName;\n const reactTagName = kebabToPascalCase(tagName);\n const fileName = component.tagName;\n\n source.push(`export { ${reactTagName} } from './${fileName}${componentSuffix}.js';`);\n }\n\n return source.join('\\n') + '\\n';\n};\n","import type { ComponentCompilerMeta } from '@stencil/core/internal';\nimport { eventListenerName, kebabToPascalCase, normalizeTypeString } from './utils/string-utils.js';\nimport type { RenderToStringOptions } from './runtime/ssr.js';\n\ninterface ReactEvent {\n originalName: string;\n name: string;\n type: string;\n}\n\nconst autogeneratedComment = `/**\n * This file was automatically generated by the Stencil React Output Target.\n * Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.\n */`;\n\nexport const createStencilReactComponents = ({\n components,\n stencilPackageName,\n customElementsDir,\n componentsTypesDir,\n hydrateModule,\n clientModule,\n serializeShadowRoot,\n transformTag,\n exportMaps,\n typesFromComponentsFile,\n}: {\n components: ComponentCompilerMeta[];\n stencilPackageName: string;\n customElementsDir: string;\n componentsTypesDir: string;\n hydrateModule?: string;\n clientModule?: string;\n serializeShadowRoot?: RenderToStringOptions['serializeShadowRoot'];\n transformTag?: boolean;\n /**\n * The Stencil project generates a package.json `exports` map, so import through its\n * entries (`<pkg>/<tag>`, `<pkg>/components`) instead of deep `dist/` paths the map would block.\n */\n exportMaps?: boolean;\n /**\n * `componentsTypesDir` points at the `types` output's `components.d.ts` (Stencil v5), so\n * event types can come from there too instead of relying on the package root exporting them.\n */\n typesFromComponentsFile?: boolean;\n}) => {\n const isSSRModule = hydrateModule && clientModule;\n const componentsTypesModule = exportMaps\n ? `${stencilPackageName}/components`\n : `${stencilPackageName}/${componentsTypesDir}`;\n\n const eventTypesModule = exportMaps || typesFromComponentsFile ? componentsTypesModule : stencilPackageName;\n\n const imports: (string | false | undefined)[] = [\n !isSSRModule && `import React from 'react';`,\n ...(hydrateModule\n ? [\n transformTag && `import { getTagTransformer } from './tag-transformer.js';`,\n `import { createComponent, type SerializeShadowRootOptions, type HydrateModule } from '@stencil/react-output-target/ssr';`,\n ]\n : [\n transformTag && `import { transformTag } from './tag-transformer.js';`,\n `import { createComponent } from '@stencil/react-output-target/runtime';`,\n ]),\n `import type { Components } from '${componentsTypesModule}';`,\n ];\n\n const exports: (string | false)[] = [];\n\n /**\n * Add imports for react client components if hydrateModule is provided.\n * This import needs a @ts-ignore comment.\n */\n if (isSSRModule) {\n imports.push(\n '// @ts-ignore - ignore potential type issues as the project is importing itself',\n `import * as clientComponents from '${clientModule}';`\n );\n }\n\n /**\n * Add the `serializeShadowRoot` variable to the file if the hydrateModule is provided.\n */\n if (hydrateModule) {\n const initializer = serializeShadowRoot\n ? JSON.stringify(serializeShadowRoot)\n : '{ default: \"declarative-shadow-dom\" }';\n\n exports.push(`export const serializeShadowRoot: SerializeShadowRootOptions = ${initializer};`);\n }\n\n const importedEvents = new Set<string>();\n\n for (const component of components) {\n const tagName = component.tagName;\n const reactTagName = kebabToPascalCase(tagName);\n const componentElement = `${reactTagName}Element`;\n const componentCustomEvent = `${reactTagName}CustomEvent`;\n\n const namedImport = [\n `${reactTagName} as ${componentElement}`,\n !isSSRModule && `defineCustomElement as define${reactTagName}`,\n ]\n .filter(Boolean)\n .join(', ');\n\n const specifier = exportMaps\n ? `${stencilPackageName}/${tagName}`\n : `${stencilPackageName}/${customElementsDir}/${tagName}.js`;\n\n imports.push(`import { ${namedImport} } from '${specifier}';`);\n\n const events: ReactEvent[] = [];\n\n for (const event of component.events || []) {\n if (event.internal || !event.complexType) {\n continue;\n }\n\n const { references = {}, original } = event.complexType;\n /**\n * Import the referenced types from the component library.\n * Stencil will automatically re-export type definitions from the components,\n * if they are used in the component's property or event types.\n */\n for (const referenceKey of Object.keys(references)) {\n /**\n * Global type references should not have an explicit import.\n * The type should be available globally.\n */\n if (references[referenceKey].location !== 'global') {\n importedEvents.add(referenceKey);\n }\n }\n\n // Always type events using the Stencil per-component CustomEvent type.\n events.push({\n originalName: event.name,\n name: eventListenerName(event.name),\n type: `EventName<${componentCustomEvent}<${normalizeTypeString(original)}>>`,\n });\n }\n\n /**\n * Import the CustomEvent type for the web component from the Stencil package.\n *\n * For example:\n * ```\n * import type { ComponentCustomEvent } from 'my-component-library';\n * ```\n */\n if (events.length) {\n importedEvents.add(componentCustomEvent);\n }\n\n const componentEventNamesType = `${reactTagName}Events`;\n\n const requiredProps = component.properties.filter((p) => p.required && !p.internal).map((p) => `'${p.name}'`);\n const requiredGeneric = requiredProps.length > 0 ? `, ${requiredProps.join(' | ')}` : '';\n const eventType =\n events.length > 0\n ? `{\\n ${events.map(({ name, type }) => `${name}: ${type}`).join(',\\n ')}\\n}`\n : 'NonNullable<unknown>';\n\n exports.push(`export type ${componentEventNamesType} = ${eventType};`);\n\n const clientComponentCall = [\n `/*@__PURE__*/ createComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}${requiredGeneric}>({`,\n ` tagName: '${tagName}',`,\n ` elementClass: ${componentElement},`,\n ` // @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project.`,\n ` react: React,`,\n ` events: ${events.length ? `{\\n ${events.map((e) => `${e.name}: '${e.originalName}'`).join(',\\n ')}\\n }` : '{}'} as ${componentEventNamesType},`,\n ` defineCustomElement: define${reactTagName},`,\n transformTag && ` transformTag,`,\n `})`,\n ]\n .filter(Boolean)\n .join('\\n');\n\n /**\n * Filter out properties that don't have an attribute.\n * These are properties with complex types and can't be serialized.\n */\n const serverProperties = component.properties\n .filter(({ attribute }) => Boolean(attribute))\n .map(({ name, attribute }) => `${name}: '${attribute}'`)\n .join(',\\n ');\n\n const serverComponentCall = [\n `/*@__PURE__*/ createComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}${requiredGeneric}>({`,\n ` tagName: '${tagName}',`,\n ` properties: {${serverProperties ? `\\n ${serverProperties}\\n ` : ''}},`,\n ` hydrateModule: typeof window === 'undefined' ? (import('${hydrateModule}') as Promise<HydrateModule>) : undefined,`,\n ` clientModule: clientComponents.${reactTagName} as StencilReactComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}${requiredGeneric}>,`,\n ` serializeShadowRoot,`,\n transformTag && ` getTagTransformer,`,\n `})`,\n ]\n .filter(Boolean)\n .join('\\n');\n\n const exportType = `StencilReactComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}${requiredGeneric}>`;\n exports.push(\n `export const ${reactTagName}: ${exportType} = ${hydrateModule ? serverComponentCall : clientComponentCall};`\n );\n }\n\n const hasEvents = Boolean(importedEvents.size);\n\n imports.push(\n hasEvents && `import type { ${Array.from(importedEvents).join(', ')} } from '${eventTypesModule}';`,\n `import type { StencilReactComponent${hasEvents ? ', EventName' : ''} } from '@stencil/react-output-target/runtime';`\n );\n\n return [\n /**\n * both files get the `use client` directive; the server file switches to the\n * server component at runtime (see runtime/ssr.tsx).\n */\n `'use client';\\n`,\n autogeneratedComment + '\\n',\n `/* eslint-disable */\\n`,\n imports.filter(Boolean).join('\\n') + '\\n',\n exports.filter(Boolean).join('\\n\\n') + '\\n',\n ].join('\\n');\n};\n","export const createTagTransformer = ({\n stencilPackageName,\n customElementsDir,\n exportMaps,\n}: {\n stencilPackageName: string;\n customElementsDir: string;\n /** Import through the package's `exports` map (`<pkg>/standalone`) instead of a deep path. */\n exportMaps?: boolean;\n}) => {\n const standaloneModule = exportMaps\n ? `${stencilPackageName}/standalone`\n : `${stencilPackageName}/${customElementsDir}/index.js`;\n return `/* eslint-disable */\n/* tslint:disable */\nimport { setTagTransformer as clientSetTagTransformer } from '${standaloneModule}';\n\nlet tagTransformer: ((tagName: string) => string) | undefined;\n\nexport const setTagTransformer = (transformer: (tagName: string) => string) => {\n clientSetTagTransformer(transformer);\n tagTransformer = transformer;\n};\n\nexport const transformTag = (tag: string): string => {\n return tagTransformer ? tagTransformer(tag) : tag;\n};\n\nexport const getTagTransformer = () => tagTransformer;\n`;\n};\n","import type { ComponentCompilerMeta } from '@stencil/core/internal';\nimport path from 'node:path';\nimport { createEsModulesComponentsFile } from './create-es-modules-components-file.js';\nimport { createStencilReactComponents } from './create-stencil-react-components.js';\nimport { createTagTransformer } from './create-tag-transformer.js';\nimport type { RenderToStringOptions } from './runtime/ssr.js';\n\nexport const createComponentWrappers = ({\n stencilPackageName,\n components,\n outDir,\n esModules,\n customElementsDir,\n componentsTypesDir,\n excludeComponents,\n hydrateModule,\n clientModule,\n excludeServerSideRenderingFor,\n serializeShadowRoot,\n transformTag,\n exportMaps,\n typesFromComponentsFile,\n}: {\n stencilPackageName: string;\n components: ComponentCompilerMeta[];\n customElementsDir: string;\n componentsTypesDir: string;\n outDir: string;\n esModules?: boolean;\n excludeComponents?: string[];\n hydrateModule?: string;\n clientModule?: string;\n excludeServerSideRenderingFor?: string[];\n serializeShadowRoot?: RenderToStringOptions['serializeShadowRoot'];\n transformTag?: boolean;\n exportMaps?: boolean;\n typesFromComponentsFile?: boolean;\n}) => {\n const files: Record<string, string> = {};\n\n const filteredComponents = components.filter((c) => {\n if (c.internal) {\n /**\n * Skip internal components\n */\n return false;\n }\n\n /**\n * Skip excluded components\n */\n return !excludeComponents?.includes(c.tagName);\n });\n\n if (filteredComponents.length === 0) {\n return files;\n }\n\n /**\n * create a single file with all components or a separate file for each component\n * @param components - the components to create the file for\n * @param filename - the filename of the file to create\n */\n function createComponentFile(components: ComponentCompilerMeta[], filename = 'components') {\n /**\n * create a single file with all components\n */\n const outputPath = path.join(outDir, `${filename}.ts`);\n\n /**\n * create a client side component\n */\n files[outputPath] = createStencilReactComponents({\n components,\n stencilPackageName,\n customElementsDir,\n componentsTypesDir,\n exportMaps,\n typesFromComponentsFile,\n transformTag,\n });\n\n /**\n * create tag-transformer file (for both client and server)\n */\n if (transformTag) {\n files[path.join(outDir, 'tag-transformer.ts')] = createTagTransformer({\n stencilPackageName,\n customElementsDir,\n exportMaps,\n });\n }\n\n /**\n * create a server side component\n */\n if (hydrateModule) {\n const outputPath = path.join(outDir, `${filename}.server.ts`);\n\n files[outputPath] = createStencilReactComponents({\n components: components.filter((c) => !excludeServerSideRenderingFor?.includes(c.tagName)),\n stencilPackageName,\n customElementsDir,\n componentsTypesDir,\n exportMaps,\n typesFromComponentsFile,\n hydrateModule,\n clientModule,\n serializeShadowRoot,\n transformTag,\n });\n }\n }\n\n if (esModules) {\n /**\n * create a separate file for each component\n */\n for (const component of filteredComponents) {\n createComponentFile([component], component.tagName);\n }\n files[path.join(outDir, 'components.ts')] = createEsModulesComponentsFile({ components: filteredComponents });\n\n /**\n * Server barrel — mirrors the client barrel but points at `*.server.js` and\n * exposes a single shared `serializeShadowRoot` so SSR consumers can\n * tree-shake per-component imports.\n */\n if (hydrateModule) {\n files[path.join(outDir, 'components.server.ts')] = createEsModulesComponentsFile({\n components: filteredComponents.filter(\n (c) => !excludeServerSideRenderingFor || !excludeServerSideRenderingFor.includes(c.tagName)\n ),\n componentSuffix: '.server',\n serializeShadowRoot,\n });\n }\n } else {\n createComponentFile(filteredComponents);\n }\n\n return files;\n};\n","import type { Config } from '@stencil/core';\nimport type { OutputTargetDistCustomElements } from '@stencil/core/internal';\nimport { isAbsolute, relative } from 'node:path';\nimport { createComponentWrappers } from './create-component-wrappers.js';\nimport type { RenderToStringOptions } from './runtime/ssr.js';\n\nexport interface ReactOutputTargetOptions {\n /**\n * Specify the output directory or path where the generated React components will be saved.\n */\n outDir: string;\n /**\n * Specify the components that should be excluded from the React output target.\n */\n excludeComponents?: string[];\n /**\n * The package name of the Stencil project.\n *\n * This value is automatically detected from the package.json file of the Stencil project.\n * If the validation fails, you can manually assign the package name.\n */\n stencilPackageName?: string;\n /**\n * The directory where the custom elements are saved.\n *\n * This value is automatically detected from the Stencil configuration file for the dist-custom-elements output target.\n * If you are working in an environment that uses absolute paths, consider setting this value manually.\n */\n customElementsDir?: string;\n /**\n * To enable server side rendering, provide the path to the hydrate module, e.g. `my-component/hydrate`.\n * By default this value is undefined and server side rendering is disabled.\n */\n hydrateModule?: string;\n /**\n * The name of the package that exports all React wrapped Stencil components for client side rendering.\n * This options is required when `hydrateModule` is set for server side rendering to work.\n */\n clientModule?: string;\n /**\n * Specify the components that should be excluded from server side rendering.\n */\n excludeServerSideRenderingFor?: string[];\n /**\n * If `true`, the output target will generate a separate ES module for each React component wrapper (better for tree-shaking).\n * @default false\n */\n esModules?: boolean;\n /**\n * Configure how Stencil serializes the components shadow root.\n * - If set to `declarative-shadow-dom` the component will be rendered within a Declarative Shadow DOM.\n * - If set to `scoped` Stencil will render the contents of the shadow root as a `scoped: true` component\n * and the shadow DOM will be created during client-side hydration.\n * - Alternatively you can mix and match the two by providing an object with `declarative-shadow-dom` and `scoped` keys,\n * the value arrays containing the tag names of the components that should be rendered in that mode.\n *\n * Examples:\n * - `{ 'declarative-shadow-dom': ['my-component-1', 'another-component'], default: 'scoped' }`\n * Render all components as `scoped` apart from `my-component-1` and `another-component`\n * - `{ 'scoped': ['an-option-component'], default: 'declarative-shadow-dom' }`\n * Render all components within `declarative-shadow-dom` apart from `an-option-component`\n * - `'scoped'` Render all components as `scoped`\n * - `false` disables shadow root serialization\n *\n * *NOTE* `true` has been deprecated in favor of `declarative-shadow-dom` and `scoped`\n * @default 'declarative-shadow-dom'\n */\n serializeShadowRoot?: RenderToStringOptions['serializeShadowRoot'];\n /**\n * Use `transformTag` to enable runtime tag name transformation for your components.\n * When enabled, the output target will import `transformTag` from your component library\n * and apply it when rendering components.\n *\n * You must export `transformTag` from the root entry of your component library:\n * ```ts\n * // src/index.ts\n * export { transformTag } from '@stencil/core';\n * ```\n *\n * @default false\n */\n transformTag?: boolean;\n}\n\nconst PLUGIN_NAME = 'react-output-target';\n\nconst DIST_CUSTOM_ELEMENTS_DEFAULT_DIR = 'dist/components';\nconst DIST_CUSTOM_ELEMENTS = 'dist-custom-elements';\nconst STANDALONE = 'standalone';\nconst HYDRATE_OUTPUT_TARGET = 'dist-hydrate-script';\nconst SSR_OUTPUT_TARGET = 'ssr';\n// Stencil v5 removed the `@stencil/core/internal` entry point, so anything that ends up in\n// our public typings is derived from the root `Config` type, which v4 and v5 both export.\ntype OutputTargetCustom = Extract<NonNullable<Config['outputTargets']>[number], { type: 'custom' }>;\ntype BuildCtx = Parameters<OutputTargetCustom['generator']>[2];\n\nconst TYPES_OUTPUT_TARGET = 'types';\nconst TYPES_DEFAULT_DIR = 'dist/types';\n\n/**\n * Turn an output directory into the form used inside an import specifier: relative to the\n * project root, with forward slashes. `path.relative()` returns backslashes on Windows, which\n * would otherwise end up in the generated imports.\n */\nconst toImportPath = (rootDir: string, dir: string): string =>\n (isAbsolute(dir) ? relative(rootDir, dir) : dir).replace(/\\\\/g, '/');\n\ninterface ReactOutputTarget extends OutputTargetCustom {\n __internal_getCustomElementsDir: () => string;\n}\n\n/**\n * Creates an output target for binding Stencil components to be used in a React context\n * @public\n * @param outputTarget the user-defined output target defined in a Stencil configuration file\n * @returns an output target that can be used by the Stencil compiler\n */\nexport const reactOutputTarget = ({\n outDir,\n esModules,\n stencilPackageName,\n excludeComponents,\n customElementsDir: customElementsDirOverride,\n hydrateModule,\n clientModule,\n excludeServerSideRenderingFor,\n serializeShadowRoot,\n transformTag,\n}: ReactOutputTargetOptions): ReactOutputTarget => {\n let customElementsDir = DIST_CUSTOM_ELEMENTS_DEFAULT_DIR;\n let componentsTypesDir = DIST_CUSTOM_ELEMENTS_DEFAULT_DIR;\n let exportMaps = false;\n let typesFromComponentsFile = false;\n return {\n type: 'custom',\n name: PLUGIN_NAME,\n validate(config) {\n const isV5 = (config.outputTargets || []).some((o: any) =>\n ['loader-bundle', 'standalone', 'ssr', 'types'].includes(o.type)\n );\n\n /**\n * When the Stencil project generates a package.json `exports` map, deep `dist/` imports\n * are blocked for consumers, so the wrappers import through the map's entries instead.\n * Stencil v5 only: v4's map has no `./components`, `./standalone` or `./ssr` entry.\n */\n exportMaps = isV5 && (config as { generateExportMaps?: boolean }).generateExportMaps === true;\n\n /**\n * In Stencil v5 every component type lives in the `types` output's `components.d.ts`, so\n * event types are imported from there too. v4 keeps importing them from the package root.\n */\n typesFromComponentsFile = isV5;\n\n /**\n * Validate the configuration to ensure that the dist-custom-elements\n * output target is defined in the Stencil configuration.\n *\n * This context is used to detect a customized output path.\n */\n if (customElementsDirOverride) {\n customElementsDir = customElementsDirOverride;\n componentsTypesDir = customElementsDirOverride;\n } else {\n const customElementsOutputTarget = (config.outputTargets || []).find(\n (o: any) => o.type === DIST_CUSTOM_ELEMENTS || o.type === STANDALONE\n ) as OutputTargetDistCustomElements;\n if (customElementsOutputTarget == null) {\n const isV5 = (config.outputTargets || []).some((o: any) =>\n ['loader-bundle', 'standalone', 'ssr', 'types'].includes(o.type)\n );\n const requiredTarget = isV5 ? STANDALONE : DIST_CUSTOM_ELEMENTS;\n throw new Error(\n `The '${PLUGIN_NAME}' requires '${requiredTarget}' output target. Add { type: '${requiredTarget}' }, to the outputTargets config.`\n );\n }\n if ((customElementsOutputTarget as any).type === STANDALONE) {\n /**\n * In Stencil v5, `Components` types are emitted by the `types` output target\n * (not by `standalone`). Resolve the types dir independently of the JS output dir.\n */\n const typesTarget = (config.outputTargets || []).find((o: any) => o.type === TYPES_OUTPUT_TARGET) as any;\n const rawTypesDir = typesTarget?.dir ?? TYPES_DEFAULT_DIR;\n const typesDir = toImportPath(config.rootDir!, rawTypesDir);\n componentsTypesDir = `${typesDir}/components`;\n // customElementsDir stays as default (dist/components) unless standalone.dir is set\n if ((customElementsOutputTarget as any).dir !== undefined) {\n const dir = (customElementsOutputTarget as any).dir;\n customElementsDir = toImportPath(config.rootDir!, dir);\n }\n } else if (customElementsOutputTarget.dir !== undefined) {\n /**\n * If the developer has configured a custom output path for the Stencil components,\n * we need to use that path when importing the components in the React components.\n * In Stencil v4 the dir is normalised to an absolute path before validate runs,\n * so convert it back to a rootDir-relative path for use in import specifiers.\n */\n const dir = customElementsOutputTarget.dir;\n customElementsDir = toImportPath(config.rootDir!, dir);\n componentsTypesDir = customElementsDir;\n }\n\n /**\n * For the legacy `dist-custom-elements` output target, validate that externalRuntime is\n * disabled so the Stencil runtime includes hydration flags.\n */\n if (\n customElementsOutputTarget.type === DIST_CUSTOM_ELEMENTS &&\n customElementsOutputTarget.externalRuntime !== false\n ) {\n throw new Error(\n `The '${PLUGIN_NAME}' requires the '${DIST_CUSTOM_ELEMENTS}' output target to have 'externalRuntime: false' set in its configuration.`\n );\n }\n }\n\n /**\n * Validate the configuration to ensure that the dist-hydrate-script\n * output target is defined in the Stencil configuration if the hydrateModule is provided.\n */\n if (hydrateModule) {\n const hydrateOutputTarget = (config.outputTargets || []).find(\n (o: any) => o.type === HYDRATE_OUTPUT_TARGET || o.type === SSR_OUTPUT_TARGET\n );\n if (hydrateOutputTarget == null) {\n const isV5 = (config.outputTargets || []).some((o: any) =>\n ['loader-bundle', 'standalone', 'ssr', 'types'].includes(o.type)\n );\n const requiredTarget = isV5 ? SSR_OUTPUT_TARGET : HYDRATE_OUTPUT_TARGET;\n throw new Error(\n `The '${PLUGIN_NAME}' requires '${requiredTarget}' output target when the 'hydrateModule' option is set. Add { type: '${requiredTarget}' }, to the outputTargets config.`\n );\n }\n\n if (clientModule == null) {\n throw new Error(\n `The '${PLUGIN_NAME}' requires the 'clientModule' option when the 'hydrateModule' option is set. Please provide the clientModule manually to the ${PLUGIN_NAME} output target.`\n );\n }\n }\n\n /**\n * Validate the configuration to detect the package name of the Stencil project.\n */\n if (stencilPackageName === undefined) {\n if (config.sys && config.packageJsonFilePath) {\n const { name: packageName } = JSON.parse(config.sys.readFileSync(config.packageJsonFilePath, 'utf8'));\n stencilPackageName = packageName;\n }\n\n if (!stencilPackageName) {\n throw new Error(\n `Unable to find the package name in the package.json file: ${config.packageJsonFilePath}. Please provide the stencilPackageName manually to the ${PLUGIN_NAME} output target.`\n );\n }\n }\n },\n async generator(_config, compilerCtx, buildCtx: BuildCtx) {\n const timespan = buildCtx.createTimeSpan(`generate ${PLUGIN_NAME} started`, true);\n\n const components = buildCtx.components;\n\n const sourceFiles = createComponentWrappers({\n outDir,\n components,\n stencilPackageName: stencilPackageName!,\n customElementsDir,\n componentsTypesDir,\n excludeComponents,\n esModules: esModules === true,\n hydrateModule,\n clientModule,\n excludeServerSideRenderingFor,\n serializeShadowRoot,\n transformTag,\n exportMaps,\n typesFromComponentsFile,\n });\n\n await Promise.all(\n Object.entries(sourceFiles).map(([filePath, sourceFile]) => compilerCtx.fs.writeFile(filePath, sourceFile))\n );\n\n timespan.finish(`generate ${PLUGIN_NAME} finished`);\n },\n __internal_getCustomElementsDir() {\n return customElementsDir;\n },\n };\n};\n"],"names":["kebabToPascalCase","str","segment","kebabToCamelCase","_","letter","slashesToCamelCase","eventListenerName","eventName","slashesConverted","normalizeTypeString","type","createEsModulesComponentsFile","components","componentSuffix","serializeShadowRoot","source","initializer","component","tagName","reactTagName","fileName","autogeneratedComment","createStencilReactComponents","stencilPackageName","customElementsDir","componentsTypesDir","hydrateModule","clientModule","transformTag","exportMaps","typesFromComponentsFile","isSSRModule","componentsTypesModule","eventTypesModule","imports","exports","importedEvents","componentElement","componentCustomEvent","namedImport","specifier","events","event","references","original","referenceKey","componentEventNamesType","requiredProps","p","requiredGeneric","eventType","name","clientComponentCall","e","serverProperties","attribute","serverComponentCall","exportType","hasEvents","createTagTransformer","createComponentWrappers","outDir","esModules","excludeComponents","excludeServerSideRenderingFor","files","filteredComponents","c","createComponentFile","filename","outputPath","path","PLUGIN_NAME","DIST_CUSTOM_ELEMENTS_DEFAULT_DIR","DIST_CUSTOM_ELEMENTS","STANDALONE","HYDRATE_OUTPUT_TARGET","SSR_OUTPUT_TARGET","TYPES_OUTPUT_TARGET","TYPES_DEFAULT_DIR","toImportPath","rootDir","dir","isAbsolute","relative","reactOutputTarget","customElementsDirOverride","config","isV5","o","customElementsOutputTarget","requiredTarget","typesTarget","rawTypesDir","packageName","_config","compilerCtx","buildCtx","timespan","sourceFiles","filePath","sour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