@stencil/react-output-target
Version:
React output target for @stencil/core components.
61 lines (53 loc) • 9.65 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("node:path"),v=require("ts-morph"),V=s=>s.toLowerCase().split("-").map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join(""),J=s=>s.replace(/-([_a-z])/g,(p,l)=>l.toUpperCase()),k=s=>s.replace(/\/([a-z])/g,(p,l)=>l.toUpperCase()),H=s=>{const p=k(s);return J(`on-${p}`)},Y=s=>s.replace(/\/\/.*$/gm,"").replace(/\n/g," ").replace(/\s{2,}/g," ").trim(),U=async({components:s,project:p,outDir:l,filename:S="components.ts",componentSuffix:m="",serializeShadowRoot:f})=>{const y=p||new v.Project({useInMemoryFileSystem:!0}),g=`/* eslint-disable */
`,h=`/**
* This file was automatically generated by the Stencil React Output Target.
* Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
*/
`,E=$.join(l||"",S),i=y.createSourceFile(E,h+g,{overwrite:!0});m&&(i.addImportDeclaration({moduleSpecifier:"@stencil/react-output-target/ssr",namedImports:[{name:"SerializeShadowRootOptions",isTypeOnly:!0}]}),i.addVariableStatement({isExported:!0,declarationKind:v.VariableDeclarationKind.Const,declarations:[{name:"serializeShadowRoot",type:"SerializeShadowRootOptions",initializer:f?JSON.stringify(f):'{ default: "declarative-shadow-dom" }'}]}));for(const T of s){const c=T.tagName,a=V(c),t=T.tagName;i.addExportDeclaration({moduleSpecifier:`./${t}${m}.js`,namedExports:[a]})}return i.organizeImports(),i.formatText(),await i.save(),i},A=({components:s,stencilPackageName:p,customElementsDir:l,componentsTypesDir:S,hydrateModule:m,clientModule:f,serializeShadowRoot:y,transformTag:g})=>{const h=new v.Project({useInMemoryFileSystem:!0}),E=`'use client';
`,i=`/**
* This file was automatically generated by the Stencil React Output Target.
* Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
*/
`,T=`/* eslint-disable */
`,a=m?[g?`import { getTagTransformer } from './tag-transformer.js';
`:"","import { createComponent, type SerializeShadowRootOptions, type HydrateModule, type ReactWebComponent } from '@stencil/react-output-target/ssr';"].filter(Boolean).join(`
`):"import { createComponent } from '@stencil/react-output-target/runtime';",t=g?`import { transformTag } from './tag-transformer.js';
`:"",e=h.createSourceFile("component.ts",`${E}${i}${T}
import React from 'react';
${a}
import type { EventName, StencilReactComponent } from '@stencil/react-output-target/runtime';
${t}
import type { Components } from "${p}/${S}";
`);m&&f&&e.addImportDeclaration({moduleSpecifier:f,namespaceImport:"clientComponents"}),m&&e.addVariableStatement({isExported:!0,declarationKind:v.VariableDeclarationKind.Const,declarations:[{name:"serializeShadowRoot",type:"SerializeShadowRootOptions",initializer:y?JSON.stringify(y):'{ default: "declarative-shadow-dom" }'}]});for(const u of s){const o=u.tagName,n=V(o),d=`${n}Element`,N=`${n}CustomEvent`;e.addImportDeclaration({moduleSpecifier:`${p}/${l}/${o}.js`,namedImports:[{name:n,alias:d},{name:"defineCustomElement",alias:`define${n}`}]});const _=(u.events||[]).filter(r=>r.internal===!1),w=[],j=new Set;let D=!1;for(const r of _){if(Object.keys(r.complexType.references).length>0)for(const O of Object.keys(r.complexType.references))!(r.complexType.references[O].location==="global")&&!j.has(O)&&(j.add(O),e.addImportDeclaration({moduleSpecifier:p,namedImports:[{name:O,isTypeOnly:!0}]}));D||(D=!0,e.addImportDeclaration({moduleSpecifier:p,namedImports:[{name:N,isTypeOnly:!0}]})),w.push({originalName:r.name,name:H(r.name),type:`EventName<${N}<${Y(r.complexType.original)}>>`})}const b=`${n}Events`,F=u.properties.filter(r=>r.required&&!r.internal).map(r=>`'${r.name}'`),I=F.length>0?`, ${F.join(" | ")}`:"";e.addTypeAlias({isExported:!0,name:b,type:w.length>0?`{ ${w.map(r=>`${r.name}: ${r.type}`).join(`,
`)} }`:"NonNullable<unknown>"});const L=g?`,
transformTag`:"",M=`/*@__PURE__*/ createComponent<${d}, ${b}, Components.${n}${I}>({
tagName: '${o}',
elementClass: ${d},
// @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project.
react: React,
events: {${w.map(r=>`${r.name}: '${r.originalName}'`).join(`,
`)}} as ${b},
defineCustomElement: define${n}${L}
})`,G=g?`,
getTagTransformer`:"",K=`/*@__PURE__*/ createComponent<${d}, ${b}, Components.${n}${I}>({
tagName: '${o}',
properties: {${u.properties.filter(r=>!!r.attribute).map(r=>`${r.name}: '${r.attribute}'`).join(`,
`)}},
hydrateModule: typeof window === 'undefined' ? (import('${m}') as Promise<HydrateModule>) : undefined,
clientModule: clientComponents.${n} as StencilReactComponent<${d}, ${b}, Components.${n}${I}>,
serializeShadowRoot${G}
})`;e.addVariableStatement({isExported:!0,declarationKind:v.VariableDeclarationKind.Const,declarations:[{name:n,type:`StencilReactComponent<${d}, ${b}, Components.${n}${I}>`,initializer:m?K:M}]})}if(e.organizeImports(),m&&f){const u=e.getImportDeclarations().find(o=>{var n;return((n=o.getNamespaceImport())==null?void 0:n.getText())==="clientComponents"});u&&e.insertText(u.getStart(),`// @ts-ignore - ignore potential type issues as the project is importing itself
`)}return e.formatText(),e.getFullText()},B=({stencilPackageName:s,customElementsDir:p})=>`/* eslint-disable */
/* tslint:disable */
import { setTagTransformer as clientSetTagTransformer } from '${s}/${p}/index.js';
let tagTransformer: ((tagName: string) => string) | undefined;
export const setTagTransformer = (transformer: (tagName: string) => string) => {
clientSetTagTransformer(transformer);
tagTransformer = transformer;
};
export const transformTag = (tag: string): string => {
return tagTransformer ? tagTransformer(tag) : tag;
};
export const getTagTransformer = () => tagTransformer;
`,W=async({stencilPackageName:s,components:p,outDir:l,esModules:S,customElementsDir:m,componentsTypesDir:f,excludeComponents:y,project:g,hydrateModule:h,clientModule:E,excludeServerSideRenderingFor:i,serializeShadowRoot:T,transformTag:c})=>{const a=[],t=p.filter(o=>!(o.internal===!0||y!=null&&y.includes(o.tagName)));if(t.length===0)return[];const e={};function u(o,n="components"){const d=$.join(l,`${n}.ts`),N=A({components:o,stencilPackageName:s,customElementsDir:m,componentsTypesDir:f,transformTag:c});if(e[d]=N,c){const _=$.join(l,"tag-transformer.ts");e[_]=B({stencilPackageName:s,customElementsDir:m})}if(h){const _=$.join(l,`${n}.server.ts`),w=A({components:o.filter(j=>!i||!i.includes(j.tagName)),stencilPackageName:s,customElementsDir:m,componentsTypesDir:f,hydrateModule:h,clientModule:E,serializeShadowRoot:T,transformTag:c});e[_]=w}}if(S){for(const n of t)u([n],n.tagName);const o=await U({components:t,project:g,outDir:l});if(a.push(o),h){const n=await U({components:t.filter(d=>!i||!i.includes(d.tagName)),project:g,outDir:l,filename:"components.server.ts",componentSuffix:".server",serializeShadowRoot:T});a.push(n)}}else u(t);return await Promise.all(Object.entries(e).map(async([o,n])=>{const d=g.createSourceFile(o,n,{overwrite:!0});await d.save(),a.push(d)})),a},C="react-output-target",x="dist/components",R="dist-custom-elements",P="standalone",z="dist-hydrate-script",q="ssr",Q="types",X="dist/types",Z=({outDir:s,esModules:p,stencilPackageName:l,excludeComponents:S,customElementsDir:m,hydrateModule:f,clientModule:y,excludeServerSideRenderingFor:g,serializeShadowRoot:h,transformTag:E})=>{let i=x,T=x;return{type:"custom",name:C,validate(c){if(m)i=m,T=m;else{const a=(c.outputTargets||[]).find(t=>t.type===R||t.type===P);if(a==null){const e=(c.outputTargets||[]).some(u=>["loader-bundle","standalone","ssr","types"].includes(u.type))?P:R;throw new Error(`The '${C}' requires '${e}' output target. Add { type: '${e}' }, to the outputTargets config.`)}if(a.type===P){const t=(c.outputTargets||[]).find(o=>o.type===Q),e=(t==null?void 0:t.dir)??X;if(T=`${$.isAbsolute(e)?$.relative(c.rootDir,e):e}/components`,a.dir!==void 0){const o=a.dir;i=$.isAbsolute(o)?$.relative(c.rootDir,o):o}}else if(a.dir!==void 0){const t=a.dir;i=$.isAbsolute(t)?$.relative(c.rootDir,t):t,T=i}if(a.type===R&&a.externalRuntime!==!1)throw new Error(`The '${C}' requires the '${R}' output target to have 'externalRuntime: false' set in its configuration.`)}if(f){if((c.outputTargets||[]).find(t=>t.type===z||t.type===q)==null){const e=(c.outputTargets||[]).some(u=>["loader-bundle","standalone","ssr","types"].includes(u.type))?q:z;throw new Error(`The '${C}' requires '${e}' output target when the 'hydrateModule' option is set. Add { type: '${e}' }, to the outputTargets config.`)}if(y==null)throw new Error(`The '${C}' requires the 'clientModule' option when the 'hydrateModule' option is set. Please provide the clientModule manually to the ${C} output target.`)}if(l===void 0){if(c.sys&&c.packageJsonFilePath){const{name:a}=JSON.parse(c.sys.readFileSync(c.packageJsonFilePath,"utf8"));l=a}if(!l)throw new Error(`Unable to find the package name in the package.json file: ${c.packageJsonFilePath}. Please provide the stencilPackageName manually to the ${C} output target.`)}},async generator(c,a,t){const e=t.createTimeSpan(`generate ${C} started`,!0),u=t.components,o=new v.Project,n=await W({outDir:s,components:u,stencilPackageName:l,customElementsDir:i,componentsTypesDir:T,excludeComponents:S,esModules:p===!0,project:o,hydrateModule:f,clientModule:y,excludeServerSideRenderingFor:g,serializeShadowRoot:h,transformTag:E});await Promise.all(n.map(d=>a.fs.writeFile(d.getFilePath(),d.getFullText()))),e.finish(`generate ${C} finished`)},__internal_getCustomElementsDir(){return i}}};exports.reactOutputTarget=Z;
//# sourceMappingURL=index.cjs.map