Skip to content

Commit

Permalink
feat: Preact versioning (#393)
Browse files Browse the repository at this point in the history
* remove preact version parameters

* consolidate import logic

* jsdoc

* optional config

* bump Preact version

* fix Preact import aliasing
  • Loading branch information
andy-haynes committed Apr 2, 2024
1 parent 9cf45f9 commit a4307ab
Show file tree
Hide file tree
Showing 11 changed files with 71 additions and 84 deletions.
4 changes: 0 additions & 4 deletions apps/web/src/components/WebEngineVariants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import { useEffect, useState } from 'react';
import { useComponentSourcesStore } from '@/stores/component-sources';
import { useContainerMessagesStore } from '@/stores/container-messages';

const PREACT_VERSION = '10.17.1';

interface WebEnginePropsVariantProps {
account: AccountState | null;
rootComponentPath: string;
Expand All @@ -33,7 +31,6 @@ export function WebEngine({
showContainerBoundaries: flags?.showContainerBoundaries,
},
flags,
preactVersion: PREACT_VERSION,
hooks: {
containerSourceCompiled: ({ componentPath, rawSource }) =>
addSource(componentPath, rawSource),
Expand Down Expand Up @@ -95,7 +92,6 @@ export function SandboxWebEngine({
showContainerBoundaries: flags?.showContainerBoundaries,
},
flags,
preactVersion: PREACT_VERSION,
hooks: {
containerSourceCompiled: ({ componentPath, rawSource }) =>
addSource(componentPath, rawSource),
Expand Down
10 changes: 4 additions & 6 deletions packages/application/src/hooks/useCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function useCompiler({
config,
localComponents,
}: {
config: WebEngineConfiguration;
config?: WebEngineConfiguration;
localComponents?: { [path: string]: BOSModule };
}) {
const [compiler, setCompiler] = useState<CompilerWorker | null>(null);
Expand All @@ -33,15 +33,13 @@ export function useCompiler({
compiler.postMessage({
action: 'init',
localComponents,
preactVersion: config.preactVersion,
enableBlockHeightVersioning: config.flags?.enableBlockHeightVersioning,
enableBlockHeightVersioning: config?.flags?.enableBlockHeightVersioning,
});
}, [
compiler,
config.flags?.bosLoaderUrl,
config.preactVersion,
localComponents,
config.flags?.enableBlockHeightVersioning,
config?.flags?.bosLoaderUrl,
config?.flags?.enableBlockHeightVersioning,
]);

return compiler;
Expand Down
23 changes: 3 additions & 20 deletions packages/application/src/hooks/useComponents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ export function useComponents({
[components]
);

const hooks = { ...config.hooks } || {};
const { flags, preactVersion } = config;
const hooks = { ...config?.hooks } || {};

useEffect(() => {
setIsValidRootComponentPath(
Expand All @@ -55,7 +54,7 @@ export function useComponents({
}, [rootComponentPath]);

hooks.componentRendered = (componentId: string) => {
config.hooks?.componentRendered?.(componentId);
config?.hooks?.componentRendered?.(componentId);
setComponents((currentComponents) => ({
...currentComponents,
[componentId]: {
Expand Down Expand Up @@ -92,21 +91,6 @@ export function useComponents({

hooks?.containerSourceCompiled?.(data);

// set the Preact import maps
// TODO find a better place for this
const preactImportBasePath = `https://esm.sh/preact@${preactVersion}`;
importedModules.set('preact', preactImportBasePath);
importedModules.set('preact/', `${preactImportBasePath}/`);
importedModules.set('react', `${preactImportBasePath}/compat`);
importedModules.set('react-dom', `${preactImportBasePath}/compat`);

for (const moduleName of importedModules.keys()) {
const [lib, subpath] = moduleName.split('/');
if (subpath && ['preact', 'react-dom'].includes(lib)) {
importedModules.delete(moduleName);
}
}

const component = {
...components[componentId],
componentId,
Expand All @@ -131,8 +115,7 @@ export function useComponents({
rootComponentSource,
error,
isValidRootComponentPath,
flags?.bosLoaderUrl,
preactVersion,
config?.flags?.bosLoaderUrl,
]);

return {
Expand Down
2 changes: 1 addition & 1 deletion packages/application/src/hooks/useWebEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function useWebEngine({
addComponent,
compiler,
components,
debug: config.debug,
debug: config?.debug,
getComponentRenderCount,
hooks,
});
Expand Down
10 changes: 1 addition & 9 deletions packages/application/src/hooks/useWebEngineSandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export function useWebEngineSandbox({
rootComponentPath,
}: UseWebEngineSandboxParams) {
const [nonce, setNonce] = useState('');
const preactVersion = config.preactVersion;

const { appendStylesheet, resetContainerStylesheet } = useCss();
const compiler = useCompiler({ config, localComponents });
Expand Down Expand Up @@ -50,14 +49,7 @@ export function useWebEngineSandbox({
action: 'execute',
componentId: rootComponentPath,
});
}, [
compiler,
domRoots,
localComponents,
preactVersion,
rootComponentPath,
setComponents,
]);
}, [compiler, domRoots, localComponents, rootComponentPath, setComponents]);

return {
components,
Expand Down
3 changes: 1 addition & 2 deletions packages/application/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export interface CompilerWorker extends Omit<Worker, 'postMessage'> {
}

export interface UseWebEngineParams {
config: WebEngineConfiguration;
config?: WebEngineConfiguration;
rootComponentPath?: string;
}

Expand All @@ -141,7 +141,6 @@ export interface WebEngineConfiguration {
debug?: WebEngineDebug;
flags?: WebEngineFlags;
hooks?: WebEngineHooks;
preactVersion: string;
}

export interface WebEngineFlags {
Expand Down
38 changes: 7 additions & 31 deletions packages/compiler/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { SocialDb } from '@bos-web-engine/social-db';

import { buildComponentSource } from './component';
import { CssParser } from './css';
import { buildModuleImports, buildModulePackageUrl } from './import';
import {
buildContainerModuleImports,
buildModuleImportStatements,
} from './import';
import { fetchComponentSources } from './source';
import { transpileSource } from './transpile';
import type {
Expand All @@ -30,7 +33,6 @@ export class ComponentCompiler {
private bosSourceCache: Map<string, Promise<BOSModule | null>>;
private compiledSourceCache: Map<string, TranspiledCacheEntry | null>;
private readonly sendWorkerMessage: SendMessageCallback;
private preactVersion?: string;
private enableBlockHeightVersioning?: boolean;
private social: SocialDb;
private readonly cssParser: CssParser;
Expand All @@ -46,12 +48,7 @@ export class ComponentCompiler {
});
}

init({
localComponents,
preactVersion,
enableBlockHeightVersioning,
}: CompilerInitAction) {
this.preactVersion = preactVersion;
init({ localComponents, enableBlockHeightVersioning }: CompilerInitAction) {
this.enableBlockHeightVersioning = enableBlockHeightVersioning;

this.bosSourceCache.clear();
Expand Down Expand Up @@ -287,31 +284,10 @@ export class ComponentCompiler {
.flat();

// build the import map used by the container
const importedModules = containerModuleImports.reduce(
(importMap, { moduleName, modulePath }) => {
const importMapEntries = buildModulePackageUrl(
moduleName,
modulePath,
this.preactVersion!
);

if (!importMapEntries) {
return importMap;
}

const moduleEntry = importMap.get(moduleName);
if (moduleEntry) {
return importMap;
}

importMap.set(importMapEntries.moduleName, importMapEntries.url);
return importMap;
},
new Map<string, string>()
);
const importedModules = buildContainerModuleImports(containerModuleImports);

const componentSource = [
...buildModuleImports(containerModuleImports),
...buildModuleImportStatements(containerModuleImports),
...[...transformedComponents.values()].map(
({ transpiled }) => transpiled
),
Expand Down
59 changes: 54 additions & 5 deletions packages/compiler/src/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import initializeWalletSelectorPlugin from '@bos-web-engine/wallet-selector-plug

import type { ImportExpression, ModuleImport } from './types';

const PREACT_VERSION = '10.20.1';
const BWE_MODULE_URL_PREFIX = 'near://';
const PLUGIN_MODULES = new Map<string, string>([
['@bos-web-engine/social-db-plugin', initializeSocialDbPlugin.toString()],
Expand Down Expand Up @@ -78,7 +79,9 @@ const extractModuleName = (modulePath: string) => {
* Build container-level imports based on module imports across all Components
* @param moduleImports set of module imports across Components within a container
*/
export const buildModuleImports = (moduleImports: ModuleImport[]): string[] => {
export const buildModuleImportStatements = (
moduleImports: ModuleImport[]
): string[] => {
if (!moduleImports.length) {
return [];
}
Expand Down Expand Up @@ -258,12 +261,11 @@ const aggregateModuleImports = (imports: ImportExpression[]): ImportsByType => {
/**
* Build the importmap URL based on package name/URL
* @param moduleName module name specified in the import statement
* @param preactVersion version of Preact dependency
* @param modulePath module import path
*/
export const buildModulePackageUrl = (
moduleName: string,
modulePath: string,
preactVersion: string
modulePath: string
) => {
if (modulePath.startsWith('https://')) {
return {
Expand All @@ -274,6 +276,53 @@ export const buildModulePackageUrl = (

return {
moduleName,
url: `https://esm.sh/${moduleName}?alias=react:preact/compat&deps=preact@${preactVersion}`,
url: `https://esm.sh/${moduleName}?alias=react:preact/compat&external=preact`,
};
};

/**
* Given a set of module imports, construct the importmap with references to esm.sh modules
* @param containerModuleImports set of module imports across the container
*/
export const buildContainerModuleImports = (
containerModuleImports: ModuleImport[]
) => {
const importedModules = containerModuleImports.reduce(
(importMap, { moduleName, modulePath }) => {
const importMapEntries = buildModulePackageUrl(moduleName, modulePath);

if (!importMapEntries) {
return importMap;
}

const moduleEntry = importMap.get(moduleName);
if (moduleEntry) {
return importMap;
}

importMap.set(importMapEntries.moduleName, importMapEntries.url);
return importMap;
},
new Map<string, string>()
);

// set the Preact import maps
const preactImportPath = `https://esm.sh/stable/preact@${PREACT_VERSION}`;
const preactCompatPath = `https://esm.sh/preact@${PREACT_VERSION}/compat`;
importedModules.set('preact', preactImportPath);
importedModules.set('react', preactCompatPath);
importedModules.set('react-dom', preactCompatPath);

// remove conflicting imports from source
for (const moduleName of importedModules.keys()) {
const [lib, subpath] = moduleName.split('/');
if (subpath && ['preact', 'react-dom'].includes(lib)) {
importedModules.delete(moduleName);
}
}

importedModules.set('preact/compat', preactCompatPath);
importedModules.set('preact/compat/', `${preactCompatPath}/`);

return importedModules;
};
1 change: 0 additions & 1 deletion packages/compiler/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export type LocalComponentMap = { [path: string]: BOSModule };
export interface CompilerInitAction {
action: 'init';
localComponents?: LocalComponentMap;
preactVersion: string;
enableBlockHeightVersioning?: boolean;
}

Expand Down
4 changes: 0 additions & 4 deletions packages/sandbox/src/components/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { useEffect, useState } from 'react';
import s from './Preview.module.css';
import {
DEFAULT_SANDBOX_ACCOUNT_ID,
PREACT_VERSION,
PREVIEW_UPDATE_DEBOUNCE_DELAY,
} from '../constants';
import { useDebouncedValue } from '../hooks/useDebounced';
Expand Down Expand Up @@ -42,9 +41,6 @@ export function Preview() {
const accountId = account?.accountId ?? DEFAULT_SANDBOX_ACCOUNT_ID;

const { components, nonce } = useWebEngineSandbox({
config: {
preactVersion: PREACT_VERSION,
},
localComponents,
rootComponentPath,
});
Expand Down
1 change: 0 additions & 1 deletion packages/sandbox/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export const FILE_EXTENSIONS = ['tsx', 'module.css'] as const;
export type FileExtension = (typeof FILE_EXTENSIONS)[number];

export const DEFAULT_SANDBOX_ACCOUNT_ID = 'bwe-web.near';
export const PREACT_VERSION = '10.17.1';
export const FILE_EXTENSION_REGEX = new RegExp(
`\\.(${FILE_EXTENSIONS.join('|')})$`
);
Expand Down

0 comments on commit a4307ab

Please sign in to comment.