@wrdagency/react-islands 1.0.5 → 2.0.1

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.
package/dist/index.js CHANGED
@@ -1,142 +1,102 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var __async = (__this, __arguments, generator) => {
30
- return new Promise((resolve, reject) => {
31
- var fulfilled = (value) => {
32
- try {
33
- step(generator.next(value));
34
- } catch (e) {
35
- reject(e);
36
- }
37
- };
38
- var rejected = (value) => {
39
- try {
40
- step(generator.throw(value));
41
- } catch (e) {
42
- reject(e);
43
- }
44
- };
45
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
46
- step((generator = generator.apply(__this, __arguments)).next());
47
- });
48
- };
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { createRoot } from 'react-dom/client';
3
+ import { useRef, useEffect } from 'react';
49
4
 
50
- // src/index.ts
51
- var src_exports = {};
52
- __export(src_exports, {
53
- ReactIslandsWebpackPlugin: () => ReactIslandsWebpackPlugin,
54
- createIsland: () => createIsland
55
- });
56
- module.exports = __toCommonJS(src_exports);
57
- var import_webpack = require("webpack");
58
- var import_tmp = __toESM(require("tmp"));
59
- var import_server = require("react-dom/server");
60
- var import_client = require("react-dom/client");
61
- import_tmp.default.setGracefulCleanup();
62
- var ReactIslandsWebpackPlugin = class _ReactIslandsWebpackPlugin {
63
- createSubCompiler(dir, entry, options) {
64
- const plugins = options.plugins.filter(
65
- (plugin) => !(plugin instanceof _ReactIslandsWebpackPlugin)
66
- );
67
- const compilerOptions = {
68
- mode: "development",
69
- target: "node",
70
- context: process.cwd(),
71
- entry,
72
- output: {
73
- libraryTarget: "commonjs",
74
- path: dir,
75
- filename: "[name].js"
76
- },
77
- module: options.module,
78
- stats: false,
79
- devtool: false,
80
- optimization: {
81
- minimize: false
82
- },
83
- plugins
5
+ /**
6
+ * Internal component for rendering raw HTML in a React component.
7
+ */
8
+ function RawHTML({ html }) {
9
+ const ref = useRef(null);
10
+ // important to not have ANY deps
11
+ useEffect(() => {
12
+ if (ref.current) {
13
+ ref.current.outerHTML = html;
14
+ }
15
+ }, []);
16
+ return jsx("script", { ref: ref });
17
+ }
18
+ /**
19
+ * Create a higher-order component with certain fixed.
20
+ *
21
+ * Useful for quickly creating multiple variants of the same component to use as islands.
22
+ *
23
+ * @param component FC<T>
24
+ * @param setProps Partial<T>
25
+ * @returns FC<T>
26
+ */
27
+ function withProps(component, setProps) {
28
+ return (props) => {
29
+ return component({ ...props, ...setProps });
84
30
  };
85
- return (0, import_webpack.webpack)(compilerOptions);
86
- }
87
- apply(compiler) {
88
- return __async(this, null, function* () {
89
- let components = [];
90
- const options = compiler.options;
91
- const entry = typeof options.entry === "function" ? yield options.entry() : options.entry;
92
- const { name: dir } = import_tmp.default.dirSync();
93
- const { RawSource } = compiler.webpack.sources;
94
- compiler.hooks.run.tapAsync(
95
- "ReactIslandsWebpackPlugin",
96
- (compiler2, callback) => {
97
- components = Object.keys(entry);
98
- const subCompiler = this.createSubCompiler(dir, entry, options);
99
- subCompiler.run((err, stats) => {
100
- if (err) {
101
- console.error(err);
102
- throw new Error("ReactIslandsWebpackPlugin: Error during compile.");
103
- }
104
- if (stats == null ? void 0 : stats.hasErrors()) {
105
- console.log(stats == null ? void 0 : stats.toString());
106
- throw new Error("ReactIslandsWebpackPlugin: Failed to compile.");
31
+ }
32
+ /**
33
+ * Checks if the current script is running in a pre-render.
34
+ *
35
+ * @returns boolean
36
+ */
37
+ function isServer() {
38
+ return !(typeof window != "undefined" && window.document);
39
+ }
40
+
41
+ class Island {
42
+ component;
43
+ renderOptions;
44
+ constructor(component, opts = {}) {
45
+ this.component = component;
46
+ this.renderOptions = {
47
+ shouldHydrate: opts.shouldHydrate ?? true,
48
+ multiple: opts.multiple ?? false,
49
+ keepChildren: opts.keepChildren ?? false,
50
+ };
51
+ }
52
+ getProps(element) {
53
+ const { keepChildren } = this.renderOptions;
54
+ let props = {};
55
+ try {
56
+ const json = element.dataset.props || "{}";
57
+ if (json) {
58
+ const parsed = JSON.parse(json);
59
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
60
+ throw new Error(`Parsed JSON is not a valid dictionary object: '${json}'`);
61
+ }
62
+ if (parsed) {
63
+ // Ignore null.
64
+ props = parsed;
65
+ }
107
66
  }
108
- callback();
109
- console.log("ReactIslandsWebpackPlugin: Compilation complete.");
110
- });
111
67
  }
112
- );
113
- compiler.hooks.thisCompilation.tap(
114
- "ReactIslandsWebpackPlugin",
115
- (compilation) => {
116
- for (const name of components) {
117
- const file = `${dir}/${name}.js`;
118
- const { default: component } = require(file);
119
- const markup = (0, import_server.renderToStaticMarkup)(component());
120
- compilation.emitAsset(`${name}.html`, new RawSource(markup));
121
- }
68
+ catch (e) {
69
+ console.warn("Could not parse JSON props for React Island.");
70
+ console.error(e);
71
+ }
72
+ if (keepChildren) {
73
+ props.children = jsx(RawHTML, { html: element.innerHTML });
122
74
  }
123
- );
124
- });
125
- }
126
- };
127
- function createIsland(name, Component) {
128
- const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
129
- if (isBrowser) {
130
- document.querySelectorAll(`[data-react-component="${name}"]`).forEach((element) => {
131
- const propsJSON = element.getAttribute("data-react-props") || "{}";
132
- const props = JSON.parse(propsJSON);
133
- (0, import_client.hydrateRoot)(element, Component(props));
134
- });
135
- }
75
+ return props;
76
+ }
77
+ getRoots(name) {
78
+ const selector = `[data-island="${name}"]`;
79
+ const { multiple } = this.renderOptions;
80
+ const nodes = [...document.querySelectorAll(selector)];
81
+ if (!nodes) {
82
+ console.warn(`Could not render React Island because DOM node (${selector}) could not be found.`);
83
+ return [];
84
+ }
85
+ if (nodes.length > 1 && !multiple) {
86
+ console.warn(`Multiple elements matched React Island selector (${selector}) but multiple was not enabled. Choosing first element as root.`);
87
+ return [nodes[0]];
88
+ }
89
+ return nodes;
90
+ }
91
+ render(name) {
92
+ this.getRoots(name).forEach((element) => {
93
+ const props = this.getProps(element);
94
+ const Component = withProps(this.component, props);
95
+ const root = createRoot(element);
96
+ root.render(jsx(Component, {}));
97
+ return root;
98
+ });
99
+ }
136
100
  }
137
- // Annotate the CommonJS export names for ESM import in node:
138
- 0 && (module.exports = {
139
- ReactIslandsWebpackPlugin,
140
- createIsland
141
- });
142
- //# sourceMappingURL=index.js.map
101
+
102
+ export { Island, isServer, withProps };
package/package.json CHANGED
@@ -1,34 +1,57 @@
1
1
  {
2
+ "type": "module",
2
3
  "name": "@wrdagency/react-islands",
3
- "version": "1.0.5",
4
+ "version": "2.0.1",
4
5
  "description": "",
5
6
  "main": "./dist/index.js",
6
- "module": "./dist/index.mjs",
7
- "types": "./dist/index.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "src",
10
+ "bin"
11
+ ],
12
+ "bin": {
13
+ "react-islands": "./bin/index.cjs"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
8
21
  "scripts": {
9
- "build": "tsup"
22
+ "build": "npx rollup -c rollup.config.js"
10
23
  },
11
24
  "keywords": [
12
25
  "react",
13
- "webpack",
14
- "static"
26
+ "islands"
15
27
  ],
16
28
  "author": "Kyle Thomas Cooper @ WRD",
17
29
  "license": "MIT",
18
30
  "devDependencies": {
19
- "@types/react-dom": "^18.2.23",
20
- "@types/tmp": "^0.2.6",
21
- "@types/webpack": "^5.28.5",
22
- "tsup": "^8.0.2",
23
- "typescript": "^5.4.3"
31
+ "@rollup/plugin-commonjs": "^28.0.6",
32
+ "@rollup/plugin-json": "^6.1.0",
33
+ "@rollup/plugin-node-resolve": "^16.0.1",
34
+ "@rollup/plugin-replace": "^6.0.2",
35
+ "@rollup/plugin-terser": "^0.4.4",
36
+ "@rollup/plugin-typescript": "^12.1.4",
37
+ "@types/command-line-args": "^5.2.3",
38
+ "@types/command-line-usage": "^5.0.4",
39
+ "@types/react": "^19.1.8",
40
+ "@types/react-dom": "^19.1.6",
41
+ "command-line-args": "^6.0.1",
42
+ "command-line-usage": "^7.0.3",
43
+ "rollup": "^4.45.1",
44
+ "rollup-plugin-dts": "^6.2.1",
45
+ "rollup-plugin-typescript-paths": "^1.5.0",
46
+ "tslib": "^2.8.1",
47
+ "typescript": "^5.4.3",
48
+ "yocto-spinner": "^1.0.0"
24
49
  },
25
50
  "repository": {
26
51
  "type": "git",
27
52
  "url": "https://github.com/kyletcooper/react-islands"
28
53
  },
29
54
  "peerDependencies": {
30
- "react-dom": "^18.2.0",
31
- "tmp": "^0.2.3",
32
- "webpack": "^5.91.0"
55
+ "react-dom": "^19.1.0"
33
56
  }
34
57
  }
@@ -0,0 +1,73 @@
1
+ import { readFileSync } from "fs";
2
+ import { OutputOptions } from "rollup";
3
+ import yoctoSpinner from "yocto-spinner";
4
+ import { createCommonConfig, createRollupConfigs, runRollup } from "../rollup";
5
+ import { Command } from "../util/command";
6
+
7
+ export default new Command({
8
+ description: "Build and statically render the islands.",
9
+ args: [
10
+ {
11
+ name: "config",
12
+ type: String,
13
+ alias: "c",
14
+ // @ts-ignore
15
+ description: "The config file to use.",
16
+ defaultValue: "islands.config.json",
17
+ },
18
+ ],
19
+ callback: async (args) => {
20
+ const { config } = args;
21
+
22
+ const configJson = JSON.parse(readFileSync(config, "utf8"));
23
+
24
+ const { islands, ...restConfig } = configJson;
25
+
26
+ if (restConfig.common !== false) {
27
+ const spinner = yoctoSpinner({
28
+ text: `Creating common dependencies file...`,
29
+ }).start();
30
+
31
+ const commonRollupConfig = createCommonConfig(restConfig);
32
+ const { output, ...input } = commonRollupConfig;
33
+ const success = await runRollup(input, output as OutputOptions);
34
+
35
+ if (success) {
36
+ spinner.success(`Succeeded: common dependencies file`);
37
+ } else {
38
+ spinner.warning(`Failed: common dependencies file`);
39
+ }
40
+ }
41
+
42
+ for (const [name, input] of Object.entries(islands)) {
43
+ const spinner = yoctoSpinner({
44
+ text: `Creating island ${name}...`,
45
+ }).start();
46
+
47
+ const rollupConfigs = createRollupConfigs({
48
+ input,
49
+ name,
50
+ ...restConfig,
51
+ });
52
+
53
+ let hadFailure = false;
54
+
55
+ for (const rollupConfig of rollupConfigs) {
56
+ const { output, ...input } = rollupConfig;
57
+ const success = await runRollup(input, output as OutputOptions);
58
+
59
+ if (!success) {
60
+ hadFailure = true;
61
+ }
62
+ }
63
+
64
+ rollupConfigs.map(async (options) => {});
65
+
66
+ if (hadFailure) {
67
+ spinner.warning(`Failed island: ${name}`);
68
+ } else {
69
+ spinner.success(`Succeeded island: ${name}`);
70
+ }
71
+ }
72
+ },
73
+ });
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import build from "./commands/build";
3
+ import { commandset } from "./util/command";
4
+
5
+ commandset({
6
+ build,
7
+ });
@@ -0,0 +1,23 @@
1
+ import { exec } from "child_process";
2
+ import { promisify } from "util";
3
+
4
+ const execPromise = promisify(exec);
5
+
6
+ export const consoleExecute = async (command: string) => {
7
+ try {
8
+ const { stdout, stderr } = await execPromise(command);
9
+
10
+ if (stdout) {
11
+ console.log(stdout);
12
+ }
13
+
14
+ if (stderr) {
15
+ console.error(stderr);
16
+ }
17
+
18
+ return stdout;
19
+ } catch (e) {
20
+ console.error(e);
21
+ throw e;
22
+ }
23
+ };
@@ -0,0 +1,57 @@
1
+ export function createGlobalObject(namespace: string): string {
2
+ return namespace
3
+ .split(".")
4
+ .filter(Boolean)
5
+ .map((_, index, levels) => {
6
+ const path = "window." + levels.slice(0, index + 1).join(".");
7
+ return `${path} = ${path} || {}`;
8
+ })
9
+ .join(";\n");
10
+ }
11
+
12
+ export function assignGlobalProperty(
13
+ namespace: string,
14
+ property: string,
15
+ value: string
16
+ ): string {
17
+ const namespacing = createGlobalObject(namespace);
18
+ return `${namespacing};\nwindow.${namespace}['${property}'] = ${value};\n`;
19
+ }
20
+
21
+ export function importPackage(packageName: string): string {
22
+ return `import * as ${packageNameToProperty(
23
+ packageName
24
+ )} from "${packageName}";\n`;
25
+ }
26
+
27
+ export function importAndGlobalisePackage(
28
+ packageName: string,
29
+ globalName: string
30
+ ): string {
31
+ let str = "";
32
+
33
+ str += importPackage(packageName);
34
+ str += `${globalName} = ${packageNameToProperty(packageName)};\n`;
35
+
36
+ return str;
37
+ }
38
+
39
+ export function packageNameToProperty(packageName: string): string {
40
+ return packageName
41
+ .replace(/^@/, "")
42
+ .replace(/\//g, "_")
43
+ .replace(/[-_](.)/g, (_, c) => c.toUpperCase())
44
+ .replace(/^[a-z]/, (c) => c.toUpperCase());
45
+ }
46
+
47
+ export function renderComponentToFile(
48
+ filename: string,
49
+ component: string
50
+ ): string {
51
+ return `var server = require('react-dom/server');
52
+ var fs = require('node:fs/promises');
53
+ var path = require('node:path');
54
+ const html = server.renderToString( module.exports.component( {} ) );
55
+ const file = path.resolve(__dirname, '${filename}');
56
+ fs.writeFile(file, html, { flag: "w+" });`;
57
+ }
@@ -0,0 +1,178 @@
1
+ import commonjsPlugin from "@rollup/plugin-commonjs";
2
+ import resolvePlugin from "@rollup/plugin-node-resolve";
3
+ import replacePlugin from "@rollup/plugin-replace";
4
+ import terserPlugin from "@rollup/plugin-terser";
5
+ import typescriptPlugin from "@rollup/plugin-typescript";
6
+ import path from "path";
7
+ import {
8
+ InputOptions,
9
+ ModuleFormat,
10
+ OutputOptions,
11
+ Plugin,
12
+ rollup,
13
+ RollupBuild,
14
+ RollupOptions,
15
+ } from "rollup";
16
+ import { typescriptPaths as typescriptPathsPlugin } from "rollup-plugin-typescript-paths";
17
+ import * as codeGen from "./generation";
18
+ import { BuildOptions, normalizeOptions } from "./options";
19
+ import { runScriptAfterBuildPlugin } from "./plugins/runScriptAfterBuildPlugin";
20
+ import { virtualizeDependencyPlugin } from "./plugins/virtualizeDependencyPlugin";
21
+
22
+ export function createRollupConfigs(options: BuildOptions): RollupOptions[] {
23
+ const normalized = normalizeOptions(options);
24
+ const { name, input, output, minify, ssg, jsx, typescript, common } =
25
+ normalized;
26
+
27
+ const configs: (RollupOptions | null)[] = [];
28
+
29
+ const createRollupConfig = (opts: {
30
+ active?: boolean;
31
+ name?: string;
32
+ subName: string;
33
+ format: ModuleFormat;
34
+ globals?: Record<string, string>;
35
+ prefix?: (name: string) => string;
36
+ suffix?: (name: string) => string;
37
+ plugins?: Plugin[];
38
+ }): RollupOptions | null => {
39
+ const {
40
+ active = true,
41
+ name: mainName = `Islands.${name}`,
42
+ subName,
43
+ format,
44
+ globals = {},
45
+ prefix,
46
+ suffix,
47
+ plugins = [],
48
+ } = opts;
49
+
50
+ if (!active) {
51
+ return null;
52
+ }
53
+
54
+ return {
55
+ input,
56
+ external: Object.keys(globals),
57
+ jsx,
58
+ output: {
59
+ name: mainName,
60
+ globals,
61
+ format,
62
+ entryFileNames: `[name]/${subName}`,
63
+ dir: output,
64
+ banner: prefix && ((chunk) => prefix(chunk.name)),
65
+ footer: suffix && ((chunk) => suffix(chunk.name)),
66
+ },
67
+ plugins: [
68
+ resolvePlugin({
69
+ extensions: [
70
+ ".cjs",
71
+ ".mjs",
72
+ ".js",
73
+ ".json",
74
+ ".node",
75
+ ".jsx",
76
+ ".ts",
77
+ ".tsx",
78
+ ],
79
+ }),
80
+ commonjsPlugin(),
81
+ replacePlugin({
82
+ preventAssignment: true,
83
+ "process.env.NODE_ENV": JSON.stringify("production"),
84
+ }),
85
+ minify && terserPlugin(),
86
+ typescript &&
87
+ typescriptPlugin({
88
+ jsx,
89
+ }),
90
+ typescript && typescriptPathsPlugin(),
91
+ ...plugins,
92
+ ],
93
+ };
94
+ };
95
+
96
+ configs.push(
97
+ createRollupConfig({
98
+ active: true,
99
+ subName: "client.js",
100
+ format: "iife",
101
+ globals: common,
102
+ suffix: (name) => `\nwindow.Islands['${name}']?.render('${name}')`,
103
+ })
104
+ );
105
+
106
+ configs.push(
107
+ createRollupConfig({
108
+ active: ssg,
109
+ subName: "server.cjs",
110
+ format: "cjs",
111
+ suffix: () =>
112
+ codeGen.renderComponentToFile("ssg.html", "module.exports.component"),
113
+ plugins: [
114
+ runScriptAfterBuildPlugin({
115
+ deleteAfterRunning: true,
116
+ }),
117
+ ],
118
+ })
119
+ );
120
+
121
+ return configs.filter(isRollupOptions);
122
+ }
123
+
124
+ export function createCommonConfig(options: BuildOptions): RollupOptions {
125
+ const normalized = normalizeOptions(options);
126
+ const { output, minify, jsx, common } = normalized;
127
+
128
+ return {
129
+ input: "virtual-entry",
130
+ jsx,
131
+ output: {
132
+ name: "Islands._Common",
133
+ file: path.resolve(output, "common.js"),
134
+ format: "iife",
135
+ },
136
+ plugins: [
137
+ replacePlugin({
138
+ preventAssignment: true,
139
+ "process.env.NODE_ENV": JSON.stringify("production"),
140
+ }),
141
+ virtualizeDependencyPlugin({
142
+ dependencies: common,
143
+ namespace: "Islands._Common",
144
+ }),
145
+ resolvePlugin(),
146
+ commonjsPlugin(),
147
+ minify && terserPlugin(),
148
+ ],
149
+ };
150
+ }
151
+
152
+ function isRollupOptions(
153
+ config: RollupOptions | null
154
+ ): config is RollupOptions {
155
+ return config !== null;
156
+ }
157
+
158
+ export async function runRollup(
159
+ inputOptions: InputOptions,
160
+ outputOptions: OutputOptions
161
+ ) {
162
+ let bundle: RollupBuild | undefined;
163
+ let buildFailed = false;
164
+
165
+ try {
166
+ bundle = await rollup(inputOptions);
167
+ await bundle.write(outputOptions);
168
+ } catch (error) {
169
+ buildFailed = true;
170
+ console.error(error);
171
+ }
172
+
173
+ if (bundle) {
174
+ await bundle.close();
175
+ }
176
+
177
+ return !buildFailed;
178
+ }