@hyperspan/plugin-preact 0.2.1 → 1.0.0-alpha.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 (2) hide show
  1. package/package.json +2 -2
  2. package/src/index.ts +97 -93
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperspan/plugin-preact",
3
- "version": "0.2.1",
3
+ "version": "1.0.0-alpha.0",
4
4
  "description": "Hyperspan Plugin for Preact",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@hyperspan/html": "0.1.7",
32
- "@hyperspan/framework": "0.5.3"
32
+ "@hyperspan/framework": "^1.0.0-alpha"
33
33
  },
34
34
  "dependencies": {
35
35
  "preact": "^10.26.5",
package/src/index.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { clientImportMap, assetHash, ISLAND_PUBLIC_PATH } from '@hyperspan/framework/assets';
1
+ import { JS_IMPORT_MAP, JS_ISLAND_PUBLIC_PATH } from '@hyperspan/framework/client/js';
2
+ import { assetHash } from '@hyperspan/framework/utils';
2
3
  import { IS_PROD } from '@hyperspan/framework/server';
3
- import { resolve } from 'node:path';
4
+ import { join, resolve } from 'node:path';
5
+ import type { Hyperspan as HS } from '@hyperspan/framework';
4
6
 
5
7
  // External ESM = https://esm.sh/preact@10.26.4/compat
6
8
  const PREACT_ISLAND_CACHE = new Map<string, string>();
@@ -8,11 +10,11 @@ const PREACT_ISLAND_CACHE = new Map<string, string>();
8
10
  /**
9
11
  * Build Preact client JS and copy to public folder
10
12
  */
11
- async function copyPreactToPublicFolder() {
13
+ async function copyPreactToPublicFolder(config: HS.Config) {
12
14
  const sourceFile = resolve(__dirname, './preact-client.ts');
13
15
  const result = await Bun.build({
14
16
  entrypoints: [sourceFile],
15
- outdir: `./public/${ISLAND_PUBLIC_PATH}`,
17
+ outdir: join('./', config.publicDir, JS_ISLAND_PUBLIC_PATH),
16
18
  naming: IS_PROD ? '[dir]/[name]-[hash].[ext]' : undefined,
17
19
  minify: true,
18
20
  format: 'esm',
@@ -20,96 +22,97 @@ async function copyPreactToPublicFolder() {
20
22
  });
21
23
 
22
24
  const builtFileName = String(result.outputs[0].path.split('/').reverse()[0]).replace('.js', '');
23
- const builtFilePath = `${ISLAND_PUBLIC_PATH}/${builtFileName}.js`;
25
+ const builtFilePath = `${JS_ISLAND_PUBLIC_PATH}/${builtFileName}.js`;
24
26
 
25
- clientImportMap.set('preact', builtFilePath);
26
- clientImportMap.set('preact/compat', builtFilePath);
27
- clientImportMap.set('preact/hooks', builtFilePath);
28
- clientImportMap.set('preact/jsx-runtime', builtFilePath);
27
+ JS_IMPORT_MAP.set('preact', builtFilePath);
28
+ JS_IMPORT_MAP.set('preact/compat', builtFilePath);
29
+ JS_IMPORT_MAP.set('preact/hooks', builtFilePath);
30
+ JS_IMPORT_MAP.set('preact/jsx-runtime', builtFilePath);
29
31
 
30
- if (!clientImportMap.has('react')) {
31
- clientImportMap.set('react', builtFilePath);
32
- clientImportMap.set('react-dom', builtFilePath);
32
+ if (!JS_IMPORT_MAP.has('react')) {
33
+ JS_IMPORT_MAP.set('react', builtFilePath);
34
+ JS_IMPORT_MAP.set('react-dom', builtFilePath);
33
35
  }
34
36
  }
35
37
 
36
38
  /**
37
39
  * Hyperspan Preact Plugin
38
40
  */
39
- export async function preactPlugin() {
40
- // Ensure Preact can be loaded on the client
41
- if (!clientImportMap.has('preact')) {
42
- await copyPreactToPublicFolder();
43
- }
44
-
45
- // Define a Bun plugin to handle .tsx files
46
- await Bun.plugin({
47
- name: 'Hyperspan Preact Loader',
48
- async setup(build) {
49
- // when a .tsx file is imported...
50
- build.onLoad({ filter: /\.tsx$/ }, async (args) => {
51
- const jsId = assetHash(args.path);
52
-
53
- // Cache: Avoid re-processing the same file
54
- if (PREACT_ISLAND_CACHE.has(jsId)) {
55
- return {
56
- contents: PREACT_ISLAND_CACHE.get(jsId) || '',
57
- loader: 'js',
58
- };
59
- }
60
-
61
- // We need to build the file to ensure we can ship it to the client with dependencies
62
- // Ironic, right? Calling Bun.build() inside of a plugin that runs on Bun.build()?
63
- const result = await Bun.build({
64
- entrypoints: [args.path],
65
- outdir: `./public/${ISLAND_PUBLIC_PATH}`,
66
- naming: IS_PROD ? '[dir]/[name]-[hash].[ext]' : undefined,
67
- external: Array.from(clientImportMap.keys()),
68
- minify: true,
69
- format: 'esm',
70
- target: 'browser',
71
- env: 'APP_PUBLIC_*',
72
- });
41
+ export function preactPlugin(): HS.Plugin {
42
+ return async (config: HS.Config) => {
43
+ // Ensure Preact can be loaded on the client
44
+ if (!JS_IMPORT_MAP.has('preact')) {
45
+ await copyPreactToPublicFolder(config);
46
+ }
73
47
 
74
- // Add output file to import map
75
- const esmName = String(result.outputs[0].path.split('/').reverse()[0]).replace('.js', '');
76
- clientImportMap.set(esmName, `${ISLAND_PUBLIC_PATH}/${esmName}.js`);
77
-
78
- let contents = await result.outputs[0].text();
79
-
80
- // Look for the default export
81
- const RE_EXPORT_DEFAULT = /export\{([^\s]+) as default\}/;
82
- const RE_EXPORT_DEFAULT_FN = /export default function\s+([^\s]+)/;
83
- const RE_EXPORT_DEFAULT_CONST = /export default const\s+([^\s]+)/;
84
- const RE_EXPORT_DEFAULT_ANY = /export default\s+([^\s]+)/;
85
-
86
- const exportedDefault = contents.match(RE_EXPORT_DEFAULT);
87
- const exportedDefaultFn = contents.match(RE_EXPORT_DEFAULT_FN);
88
- const exportedDefaultConst = contents.match(RE_EXPORT_DEFAULT_CONST);
89
- const exportedDefaultAny = contents.match(RE_EXPORT_DEFAULT_ANY);
90
-
91
- const componentName =
92
- exportedDefault?.[1] ||
93
- exportedDefaultFn?.[1] ||
94
- exportedDefaultConst?.[1] ||
95
- exportedDefaultAny?.[1];
96
-
97
- if (!componentName) {
98
- throw new Error(
99
- `No default export found in ${args.path}. Did you forget to export a component?`
100
- );
101
- }
102
-
103
- // Add to contents so this is in the client JS as well
104
- contents = `import { h, h as __hs_h, render as __hs_render, hydrate as __hs_hydrate } from 'preact';${contents}`;
105
-
106
- // Some _interesting_ work at play here...
107
- // We have to modify the original file contents to add an __HS_PLUGIN export that the renderIsland() function can use to render the component.
108
- // 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.
109
- // 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.
110
- // 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.
111
- // 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.
112
- const moduleCode = `// hyperspan:processed
48
+ // Define a Bun plugin to handle .tsx files
49
+ await Bun.plugin({
50
+ name: 'Hyperspan Preact Loader',
51
+ async setup(build) {
52
+ // when a .tsx file is imported...
53
+ build.onLoad({ filter: /\.tsx$/ }, async (args) => {
54
+ const jsId = assetHash(args.path);
55
+
56
+ // Cache: Avoid re-processing the same file
57
+ if (PREACT_ISLAND_CACHE.has(jsId)) {
58
+ return {
59
+ contents: PREACT_ISLAND_CACHE.get(jsId) || '',
60
+ loader: 'js',
61
+ };
62
+ }
63
+
64
+ // We need to build the file to ensure we can ship it to the client with dependencies
65
+ // Ironic, right? Calling Bun.build() inside of a plugin that runs on Bun.build()?
66
+ const result = await Bun.build({
67
+ entrypoints: [args.path],
68
+ outdir: join('./', config.publicDir, JS_ISLAND_PUBLIC_PATH),
69
+ naming: IS_PROD ? '[dir]/[name]-[hash].[ext]' : undefined,
70
+ external: Array.from(JS_IMPORT_MAP.keys()),
71
+ minify: true,
72
+ format: 'esm',
73
+ target: 'browser',
74
+ env: 'APP_PUBLIC_*',
75
+ });
76
+
77
+ // Add output file to import map
78
+ const esmName = String(result.outputs[0].path.split('/').reverse()[0]).replace('.js', '');
79
+ JS_IMPORT_MAP.set(esmName, `${JS_ISLAND_PUBLIC_PATH}/${esmName}.js`);
80
+
81
+ let contents = await result.outputs[0].text();
82
+
83
+ // Look for the default export
84
+ const RE_EXPORT_DEFAULT = /export\{([^\s]+) as default\}/;
85
+ const RE_EXPORT_DEFAULT_FN = /export default function\s+([^\s]+)/;
86
+ const RE_EXPORT_DEFAULT_CONST = /export default const\s+([^\s]+)/;
87
+ const RE_EXPORT_DEFAULT_ANY = /export default\s+([^\s]+)/;
88
+
89
+ const exportedDefault = contents.match(RE_EXPORT_DEFAULT);
90
+ const exportedDefaultFn = contents.match(RE_EXPORT_DEFAULT_FN);
91
+ const exportedDefaultConst = contents.match(RE_EXPORT_DEFAULT_CONST);
92
+ const exportedDefaultAny = contents.match(RE_EXPORT_DEFAULT_ANY);
93
+
94
+ const componentName =
95
+ exportedDefault?.[1] ||
96
+ exportedDefaultFn?.[1] ||
97
+ exportedDefaultConst?.[1] ||
98
+ exportedDefaultAny?.[1];
99
+
100
+ if (!componentName) {
101
+ throw new Error(
102
+ `No default export found in ${args.path}. Did you forget to export a component?`
103
+ );
104
+ }
105
+
106
+ // Add to contents so this is in the client JS as well
107
+ contents = `import { h, h as __hs_h, render as __hs_render, hydrate as __hs_hydrate } from 'preact';${contents}`;
108
+
109
+ // Some _interesting_ work at play here...
110
+ // We have to modify the original file contents to add an __HS_PLUGIN export that the renderIsland() function can use to render the component.
111
+ // 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.
112
+ // 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.
113
+ // 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.
114
+ // 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.
115
+ const moduleCode = `// hyperspan:processed
113
116
  import { render as __hs_renderToString } from 'preact-render-to-string';
114
117
 
115
118
  // Original file contents
@@ -140,13 +143,14 @@ ${componentName}.__HS_ISLAND = {
140
143
  }
141
144
  `;
142
145
 
143
- PREACT_ISLAND_CACHE.set(jsId, moduleCode);
146
+ PREACT_ISLAND_CACHE.set(jsId, moduleCode);
144
147
 
145
- return {
146
- contents: moduleCode,
147
- loader: 'js',
148
- };
149
- });
150
- },
151
- });
148
+ return {
149
+ contents: moduleCode,
150
+ loader: 'js',
151
+ };
152
+ });
153
+ },
154
+ });
155
+ };
152
156
  }