@hyperspan/plugin-preact 0.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.
@@ -0,0 +1 @@
1
+ src/preact-client.ts
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @hyperspan/plugin-preact
2
+
3
+ Dynamic Islands With Preact
4
+
5
+ Docs: https://www.hyperspan.dev/docs/islands-architecture
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@hyperspan/plugin-preact",
3
+ "version": "0.1.0",
4
+ "description": "Hyperspan Plugin for Preact",
5
+ "main": "src/index.ts",
6
+ "types": "src/index.ts",
7
+ "public": true,
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "author": "Vance Lucas <vance@vancelucas.com>",
12
+ "license": "BSD-3-Clause",
13
+ "keywords": [],
14
+ "homepage": "https://www.hyperspan.dev/docs/islands-architecture",
15
+ "bugs": {
16
+ "url": "https://github.com/vlucas/hyperspan/issues"
17
+ },
18
+ "scripts": {
19
+ "test": "bun test"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/vlucas/hyperspan.git"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "^1.2.11",
27
+ "prettier": "^3.2.5",
28
+ "typescript": "^5.0.0"
29
+ },
30
+ "peerDependencies": {
31
+ "@hyperspan/html": "^0.0.16",
32
+ "@hyperspan/framework": "^0.0.17"
33
+ },
34
+ "dependencies": {
35
+ "preact": "^10.26.5",
36
+ "preact-render-to-string": "^6.1.0"
37
+ }
38
+ }
package/src/index.ts ADDED
@@ -0,0 +1,139 @@
1
+ import { clientImportMap, assetHash, ISLAND_PUBLIC_PATH } from '@hyperspan/framework/assets';
2
+ import { resolve } from 'node:path';
3
+
4
+ // External ESM = https://esm.sh/preact@10.26.4/compat
5
+ const PREACT_PUBLIC_FILE_PATH = ISLAND_PUBLIC_PATH + '/preact-client.js';
6
+ const PREACT_ISLAND_CACHE = new Map<string, string>();
7
+
8
+ /**
9
+ * Build Preact client JS and copy to public folder
10
+ */
11
+ async function copyPreactToPublicFolder() {
12
+ const sourceFile = resolve(__dirname, './preact-client.ts');
13
+ await Bun.build({
14
+ entrypoints: [sourceFile],
15
+ outdir: './public/' + ISLAND_PUBLIC_PATH,
16
+ minify: true,
17
+ format: 'esm',
18
+ target: 'browser',
19
+ });
20
+
21
+ clientImportMap.set('preact', '' + PREACT_PUBLIC_FILE_PATH);
22
+ clientImportMap.set('preact/compat', '' + PREACT_PUBLIC_FILE_PATH);
23
+ clientImportMap.set('preact/hooks', '' + PREACT_PUBLIC_FILE_PATH);
24
+ clientImportMap.set('preact/jsx-runtime', '' + PREACT_PUBLIC_FILE_PATH);
25
+
26
+ if (!clientImportMap.has('react')) {
27
+ clientImportMap.set('react', '.' + PREACT_PUBLIC_FILE_PATH);
28
+ clientImportMap.set('react-dom', '.' + PREACT_PUBLIC_FILE_PATH);
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Hyperspan Preact Plugin
34
+ */
35
+ export async function preactPlugin() {
36
+ // Define a Bun plugin to handle .tsx files
37
+ await Bun.plugin({
38
+ name: 'Hyperspan Preact Loader',
39
+ async setup(build) {
40
+ // when a .tsx file is imported...
41
+ build.onLoad({ filter: /\.tsx$/ }, async (args) => {
42
+ const jsId = assetHash(args.path);
43
+ let contents = await Bun.file(args.path).text();
44
+
45
+ // Cache: Avoid re-processing the same file
46
+ if (PREACT_ISLAND_CACHE.has(jsId)) {
47
+ return {
48
+ contents: PREACT_ISLAND_CACHE.get(jsId) || '',
49
+ loader: 'js',
50
+ };
51
+ }
52
+
53
+ if (contents) {
54
+ // We need to build the file to ensure we can ship it to the client with dependencies
55
+ // Ironic, right? Calling Bun.build() inside of a plugin that runs on Bun.build()?
56
+ const result = await Bun.build({
57
+ entrypoints: [args.path],
58
+ //outdir: './public/' + ISLAND_PUBLIC_PATH,
59
+ //naming: '[name]-[hash].js',
60
+ external: ['react', 'preact', 'preact/compat', 'preact/hooks', 'preact/jsx-runtime'],
61
+ minify: true,
62
+ format: 'esm',
63
+ target: 'browser',
64
+ });
65
+
66
+ contents = await result.outputs[0].text();
67
+ }
68
+
69
+ // Ensure Preact can be loaded on the client
70
+ if (!clientImportMap.has('preact')) {
71
+ await copyPreactToPublicFolder();
72
+ }
73
+
74
+ // Look for the default export
75
+ const RE_EXPORT_DEFAULT = /export\{(\w+) as default\}/;
76
+ const RE_EXPORT_DEFAULT_FN = /export default function\s+(\w+)/;
77
+ const RE_EXPORT_DEFAULT_CONST = /export default const\s+(\w+)/;
78
+ const RE_EXPORT_DEFAULT_ANY = /export default\s+(\w+)/;
79
+
80
+ const exportedDefault = contents.match(RE_EXPORT_DEFAULT);
81
+ const exportedDefaultFn = contents.match(RE_EXPORT_DEFAULT_FN);
82
+ const exportedDefaultConst = contents.match(RE_EXPORT_DEFAULT_CONST);
83
+ const exportedDefaultAny = contents.match(RE_EXPORT_DEFAULT_ANY);
84
+
85
+ const componentName =
86
+ exportedDefault?.[1] ||
87
+ exportedDefaultFn?.[1] ||
88
+ exportedDefaultConst?.[1] ||
89
+ exportedDefaultAny?.[1];
90
+
91
+ if (!componentName) {
92
+ throw new Error(
93
+ `No default export found in ${args.path}. Did you forget to export a component?`
94
+ );
95
+ }
96
+
97
+ // Add to contents so this is in the client JS as well
98
+ contents = `import { h as __hs_h, render as __hs_render, hydrate as __hs_hydrate } from 'preact';${contents}`;
99
+
100
+ // Some _interesting_ work at play here...
101
+ // We have to modify the original file contents to add an __HS_PLUGIN export that the renderIsland() function can use to render the component.
102
+ // A lot of this work actaully has to be done now, ahead of time, to ensure we use the same Preact instance to hydrate and render the component so there are no errors.
103
+ // So... we have to import the preact-render-to-string library to render the component to a string here, with simple functions to do that work and return HTML.
104
+ // All imports needed for this work are prefixed with __hs_ to avoid clashing with other imports in the module, as some of them may be duplicates.
105
+ // Finally, we need to export all of the functions that do this work in a special way so we don't change the default export or other functions in the module, so that only the Hyperspan renderIsland() function can use them.
106
+ const moduleCode = `// hyperspan:processed
107
+ import { html as __hs_html } from '@hyperspan/html';
108
+ import { render as __hs_renderToString } from 'preact-render-to-string';
109
+
110
+ // Original file contents
111
+ ${contents}
112
+
113
+ // hyperspan:preact-plugin
114
+ ${componentName}.__HS_PLUGIN = {
115
+ ssr: (props) => {
116
+ const ssrContent = __hs_renderToString(__hs_h(${componentName}, props));
117
+ const postContent = \`__hs_hydrate(__hs_h(${componentName}, \${JSON.stringify(props)}), document.getElementById("${jsId}"));\`;
118
+ return __hs_html.raw(\`<div id="${jsId}">\${ssrContent}</div><script type="module" data-source-id="${jsId}">${contents}\${postContent}</script>\`);
119
+ },
120
+ render: (props) => {
121
+ const postContent = \`__hs_render(__hs_h(${componentName}, \${JSON.stringify(props)}), document.getElementById("${jsId}"));\`;
122
+
123
+ return __hs_html.raw(
124
+ \`<div id="${jsId}"></div><script type="module" data-source-id="${jsId}">${contents}\${postContent}</script>\`
125
+ );
126
+ }
127
+ }
128
+ `;
129
+
130
+ PREACT_ISLAND_CACHE.set(jsId, moduleCode);
131
+
132
+ return {
133
+ contents: moduleCode,
134
+ loader: 'js',
135
+ };
136
+ });
137
+ },
138
+ });
139
+ }
@@ -0,0 +1,3 @@
1
+ export * from 'preact/compat';
2
+ export * from 'preact/hooks';
3
+ export { h, render, hydrate } from 'preact';
package/tsconfig.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "compileOnSave": true,
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist",
6
+ "target": "es2019",
7
+ "lib": ["ESNext", "dom", "dom.iterable"],
8
+ "module": "esnext",
9
+ "moduleResolution": "bundler",
10
+ "moduleDetection": "force",
11
+ "esModuleInterop": true,
12
+ "allowImportingTsExtensions": true,
13
+ "noEmit": true,
14
+ "composite": true,
15
+ "strict": true,
16
+ "declaration": true,
17
+ "sourceMap": true,
18
+ "downlevelIteration": true,
19
+ "skipLibCheck": true,
20
+ "allowSyntheticDefaultImports": true,
21
+ "forceConsistentCasingInFileNames": true,
22
+ "allowJs": true
23
+ },
24
+ "exclude": ["node_modules", "__tests__", "*.test.ts"]
25
+ }