@eightshift/frontend-libs-tailwind 3.5.0 → 4.0.0-beta.2

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,171 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { generateDiscovery } from './discovery.mjs';
4
+
5
+ /**
6
+ * Generate caller-defined contexts for each surface. Returns absolute module
7
+ * paths keyed by surface. Regenerate after adding or removing source files.
8
+ */
9
+ export async function generateThemeDiscovery({ root, outputDir, surfaces }) {
10
+ if (!root || !outputDir || !surfaces || typeof surfaces !== 'object') {
11
+ throw new TypeError('Expected root, outputDir and surfaces');
12
+ }
13
+
14
+ const modules = {};
15
+
16
+ for (const [surface, definitions] of Object.entries(surfaces)) {
17
+ if (!/^[\w-]+$/.test(surface) || !Array.isArray(definitions)) {
18
+ throw new TypeError('Invalid discovery surface');
19
+ }
20
+
21
+ const output = resolve(root, outputDir, `${surface}.mjs`);
22
+
23
+ await generateDiscovery({ root, output, definitions });
24
+ modules[surface] = output;
25
+ }
26
+
27
+ return modules;
28
+ }
29
+
30
+ /**
31
+ * Build a static, lazy importer map from a caller-selected Bun glob. `key`
32
+ * maps each root-relative file to its runtime lookup key. Styles are optional
33
+ * { keys, href } groups, loaded once before the corresponding importer; failed
34
+ * loads remove their link and can be retried. URLs resolve relative to the
35
+ * generated JavaScript module, matching Bun's import.meta.url behavior.
36
+ */
37
+ export async function generateThemeImporters({ root, glob, key, styles = [] }) {
38
+ if (!root || typeof glob !== 'string' || typeof key !== 'function' || !Array.isArray(styles)) {
39
+ throw new TypeError('Expected root, glob, key and styles');
40
+ }
41
+
42
+ const entries = [];
43
+ const keys = new Set();
44
+
45
+ for await (const file of new Bun.Glob(glob).scan({ cwd: root, onlyFiles: true })) {
46
+ const name = key(file);
47
+
48
+ if (typeof name !== 'string' || keys.has(name)) {
49
+ throw new TypeError(`Invalid or duplicate importer key: ${name}`);
50
+ }
51
+
52
+ keys.add(name);
53
+ entries.push([name, resolve(root, file)]);
54
+ }
55
+
56
+ entries.sort(([a], [b]) => a.localeCompare(b));
57
+ const styleByKey = new Map();
58
+
59
+ for (const [index, style] of styles.entries()) {
60
+ if (!style || !Array.isArray(style.keys) || typeof style.href !== 'string') {
61
+ throw new TypeError('Invalid importer style');
62
+ }
63
+
64
+ for (const name of style.keys) {
65
+ if (!keys.has(name) || styleByKey.has(name)) {
66
+ throw new TypeError(`Unknown or duplicate styled importer: ${name}`);
67
+ }
68
+
69
+ styleByKey.set(name, index);
70
+ }
71
+ }
72
+
73
+ const loaders = styles
74
+ .map(
75
+ ({ href }, index) =>
76
+ `let stylePromise${index};
77
+ const loadStyle${index} = () => stylePromise${index} ??= new Promise((resolve, reject) => {
78
+ const link = document.createElement('link');
79
+ link.rel = 'stylesheet';
80
+ link.href = new URL(${JSON.stringify(href)}, import.meta.url).href;
81
+ link.onload = resolve;
82
+ link.onerror = () => {
83
+ link.remove();
84
+ stylePromise${index} = undefined;
85
+ reject(new Error('Failed to load stylesheet: ' + link.href));
86
+ };
87
+ document.head.appendChild(link);
88
+ });`,
89
+ )
90
+ .join('\n');
91
+ const importers = entries.map(([name, path]) => {
92
+ const importer = `() => import(${JSON.stringify(path)})`;
93
+ const style = styleByKey.get(name);
94
+
95
+ return `${JSON.stringify(name)}: ${style === undefined ? importer : `() => loadStyle${style}().then(${importer})`}`;
96
+ });
97
+
98
+ return `${loaders}\nconst bunFrontendImporters = {${importers.join(',')}};`;
99
+ }
100
+
101
+ /**
102
+ * Transform only explicitly selected entry paths. Each entry specifies
103
+ * { path, module, imports, importStatement, replacements, prefix, remove }.
104
+ * Replacements are [literal, replacement] pairs and must occur exactly once.
105
+ * `remove` is an optional array of RegExps; remaining webpack discovery is
106
+ * rejected. `prefix` can contain the generated importer map.
107
+ */
108
+ export function themeDiscoveryPlugin({ root, entries }) {
109
+ if (!root || !Array.isArray(entries)) {
110
+ throw new TypeError('Expected root and entries');
111
+ }
112
+
113
+ const byPath = new Map();
114
+
115
+ for (const entry of entries) {
116
+ if (!entry.path || !entry.module || !Array.isArray(entry.imports) || typeof entry.importStatement !== 'string' || !Array.isArray(entry.replacements) || (entry.remove && !Array.isArray(entry.remove))) {
117
+ throw new TypeError('Invalid discovery entry');
118
+ }
119
+
120
+ const path = resolve(root, entry.path);
121
+
122
+ if (byPath.has(path)) {
123
+ throw new TypeError(`Duplicate discovery entry: ${path}`);
124
+ }
125
+
126
+ byPath.set(path, entry);
127
+ }
128
+
129
+ const replaceOnce = (source, original, replacement) => {
130
+ if (typeof original !== 'string' || !original || typeof replacement !== 'string' || source.split(original).length !== 2) {
131
+ throw new Error(`Source changed; cannot replace: ${original}`);
132
+ }
133
+
134
+ return source.replace(original, () => replacement);
135
+ };
136
+
137
+ return {
138
+ name: 'theme-discovery',
139
+ setup(builder) {
140
+ builder.onLoad({ filter: /\.[cm]?jsx?$/ }, async ({ path }) => {
141
+ const entry = byPath.get(path);
142
+
143
+ if (!entry) {
144
+ return;
145
+ }
146
+
147
+ let source = await readFile(path, 'utf8');
148
+
149
+ source = replaceOnce(source, entry.importStatement, `import { ${entry.imports.join(', ')} } from ${JSON.stringify(resolve(root, entry.module))};\n${entry.prefix || ''}`);
150
+
151
+ for (const [original, replacement] of entry.replacements) {
152
+ source = replaceOnce(source, original, replacement);
153
+ }
154
+
155
+ for (const pattern of entry.remove || []) {
156
+ if (!(pattern instanceof RegExp)) {
157
+ throw new TypeError('Removal patterns must be RegExp');
158
+ }
159
+
160
+ source = source.replace(pattern, '');
161
+ }
162
+
163
+ if (source.includes('require.context') || source.includes('dynamicImport(')) {
164
+ throw new Error(`Unsupported discovery remains in ${path}`);
165
+ }
166
+
167
+ return { contents: source, loader: 'jsx', resolveDir: dirname(path) };
168
+ });
169
+ },
170
+ };
171
+ }
package/bun/watch.mjs ADDED
@@ -0,0 +1,264 @@
1
+ import { statSync, watch } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+
4
+ /**
5
+ * Watch source paths under projectDir and run build serially after changes settle.
6
+ * Paths in sources and ignored are relative to projectDir unless absolute.
7
+ * Ignored paths exclude themselves and their descendants, including outputs.
8
+ * `ignore` optionally filters absolute event paths in addition to ignored paths.
9
+ * Returns { stop }, whose promise settles after any running build finishes.
10
+ * Build and watcher errors are passed to onError; watcher errors stop watching.
11
+ */
12
+ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => false, build, debounce = 200, initial = true, onError = console.error }) {
13
+ if (!projectDir || !Array.isArray(sources) || sources.length === 0 || !Array.isArray(ignored) || typeof ignore !== 'function' || typeof build !== 'function' || typeof onError !== 'function' || !Number.isFinite(debounce) || debounce < 0) {
14
+ throw new TypeError('watchBuild requires projectDir, sources, a build function, and a non-negative debounce.');
15
+ }
16
+
17
+ const root = resolve(projectDir);
18
+ const within = (parent, path) => {
19
+ const rel = relative(parent, path);
20
+
21
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
22
+ };
23
+ const paths = (items) =>
24
+ items.map((item) => {
25
+ if (typeof item !== 'string' || !item) {
26
+ throw new TypeError('Watch paths must be non-empty strings.');
27
+ }
28
+
29
+ const path = resolve(root, item);
30
+
31
+ if (!within(root, path)) {
32
+ throw new TypeError('Watch paths must be inside projectDir.');
33
+ }
34
+
35
+ return path;
36
+ });
37
+ const inputs = paths(sources);
38
+ const exclusions = paths(ignored);
39
+ let timer;
40
+ let running;
41
+ let pending = false;
42
+ let stopped = false;
43
+ const watchers = new Map();
44
+ const directoryStamps = new Map();
45
+ const filterDirectoryEvents = process.platform === 'darwin' && typeof Bun !== 'undefined';
46
+ const directoryStamp = (path) => {
47
+ try {
48
+ const info = statSync(path);
49
+
50
+ return info.isDirectory() ? `${info.dev}:${info.ino}:${info.mode}:${info.mtimeMs}:${info.ctimeMs}` : undefined;
51
+ } catch (error) {
52
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
53
+ return undefined;
54
+ }
55
+
56
+ throw error;
57
+ }
58
+ };
59
+
60
+ const report = (error) => {
61
+ try {
62
+ onError(error);
63
+ } catch (callbackError) {
64
+ console.error(callbackError);
65
+ }
66
+ };
67
+ const run = () => {
68
+ if (stopped || running || !pending) {
69
+ return;
70
+ }
71
+
72
+ pending = false;
73
+ running = Promise.resolve()
74
+ .then(build)
75
+ .catch(report)
76
+ .finally(() => {
77
+ running = undefined;
78
+
79
+ if (!timer) {
80
+ run();
81
+ }
82
+ });
83
+ };
84
+ const schedule = () => {
85
+ if (stopped) {
86
+ return;
87
+ }
88
+
89
+ pending = true;
90
+ clearTimeout(timer);
91
+ timer = setTimeout(() => {
92
+ timer = undefined;
93
+ run();
94
+ }, debounce);
95
+ };
96
+ const stop = async () => {
97
+ if (!stopped) {
98
+ stopped = true;
99
+ pending = false;
100
+ clearTimeout(timer);
101
+ for (const watcher of watchers.values()) {
102
+ watcher.close();
103
+ }
104
+ watchers.clear();
105
+ }
106
+
107
+ await running;
108
+ };
109
+
110
+ const onEvent = (path) => {
111
+ if (stopped) {
112
+ return;
113
+ }
114
+
115
+ if (!within(root, path) || exclusions.some((item) => within(item, path))) {
116
+ return;
117
+ }
118
+
119
+ try {
120
+ if (ignore(path)) {
121
+ return;
122
+ }
123
+ } catch (error) {
124
+ report(error);
125
+ return;
126
+ }
127
+
128
+ if (inputs.some((item) => within(item, path) || within(path, item))) {
129
+ schedule();
130
+ }
131
+ };
132
+ const refresh = () => {
133
+ if (stopped) {
134
+ return;
135
+ }
136
+ const desired = new Map();
137
+ const add = (directory, recursive, name) => {
138
+ const key = `${recursive ? 'recursive' : 'parent'}:${directory}`;
139
+ if (!desired.has(key)) {
140
+ desired.set(key, { directory, recursive, names: new Set() });
141
+ }
142
+ if (name) {
143
+ desired.get(key).names.add(name);
144
+ }
145
+ };
146
+ for (const input of inputs) {
147
+ let current = input;
148
+ let info;
149
+ while (true) {
150
+ try {
151
+ info = statSync(current);
152
+ break;
153
+ } catch (error) {
154
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') {
155
+ throw error;
156
+ }
157
+ if (current === root) {
158
+ throw error;
159
+ }
160
+ current = dirname(current);
161
+ }
162
+ }
163
+ if (current === input && info.isDirectory()) {
164
+ if (filterDirectoryEvents && !directoryStamps.has(input)) {
165
+ directoryStamps.set(input, directoryStamp(input));
166
+ }
167
+ add(input, true);
168
+ if (input !== root) {
169
+ add(dirname(input), false, basename(input));
170
+ }
171
+ } else {
172
+ const directory = current === input ? dirname(input) : current;
173
+ const next = relative(directory, input).split(sep)[0];
174
+ add(directory, false, next);
175
+ }
176
+ }
177
+ for (const [key, config] of desired) {
178
+ const existing = watchers.get(key);
179
+ if (existing) {
180
+ existing.names = config.names;
181
+ continue;
182
+ }
183
+ const watcher = watch(config.directory, { recursive: config.recursive }, (_event, filename) => {
184
+ if (!filename || stopped) {
185
+ return;
186
+ }
187
+ const name = String(filename);
188
+ if (!config.recursive && !watcher.names.has(name)) {
189
+ return;
190
+ }
191
+ const path = resolve(config.directory, name);
192
+ try {
193
+ // Bun on macOS can report unchanged watched directories as changes.
194
+ if (filterDirectoryEvents && _event === 'change') {
195
+ let directory;
196
+
197
+ if (!config.recursive && inputs.includes(path)) {
198
+ directory = path;
199
+ } else if (config.recursive && name === basename(config.directory)) {
200
+ try {
201
+ statSync(path);
202
+ } catch (error) {
203
+ if (error.code !== 'ENOENT') {
204
+ throw error;
205
+ }
206
+ directory = config.directory;
207
+ }
208
+ }
209
+
210
+ if (directory) {
211
+ const stamp = directoryStamp(directory);
212
+
213
+ if (stamp && directoryStamps.get(directory) === stamp) {
214
+ return;
215
+ }
216
+ if (stamp) {
217
+ directoryStamps.set(directory, stamp);
218
+ }
219
+ }
220
+ }
221
+ if (filterDirectoryEvents && config.recursive) {
222
+ const stamp = directoryStamp(config.directory);
223
+
224
+ if (stamp) {
225
+ directoryStamps.set(config.directory, stamp);
226
+ }
227
+ }
228
+ onEvent(path);
229
+ refresh();
230
+ } catch (error) {
231
+ report(error);
232
+ void stop();
233
+ }
234
+ });
235
+ watcher.names = config.names;
236
+ watcher.on('error', (error) => {
237
+ report(error);
238
+ void stop();
239
+ });
240
+ watchers.set(key, watcher);
241
+ }
242
+ for (const [key, watcher] of watchers) {
243
+ if (!desired.has(key)) {
244
+ watcher.close();
245
+ watchers.delete(key);
246
+ }
247
+ }
248
+ };
249
+ try {
250
+ refresh();
251
+ } catch (error) {
252
+ for (const watcher of watchers.values()) {
253
+ watcher.close();
254
+ }
255
+ throw error;
256
+ }
257
+
258
+ if (initial) {
259
+ pending = true;
260
+ run();
261
+ }
262
+
263
+ return { stop };
264
+ }
@@ -0,0 +1,220 @@
1
+ import { createRequire } from 'node:module';
2
+ import { dirname, isAbsolute, resolve } from 'node:path';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { promisify } from 'node:util';
5
+ import { execFile } from 'node:child_process';
6
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
7
+
8
+ const execFileAsync = promisify(execFile);
9
+ const externals = {
10
+ moment: ['moment', 'moment', 'commonjs'],
11
+ jquery: ['jQuery', 'jquery', 'commonjs'],
12
+ lodash: ['lodash', 'lodash', 'commonjs'],
13
+ 'lodash-es': ['lodash', 'lodash', 'esm'],
14
+ '@babel/runtime/regenerator': ['regeneratorRuntime', 'regenerator-runtime', 'commonjs'],
15
+ react: ['React', 'react', 'react'],
16
+ 'react-dom': ['ReactDOM', 'react-dom', 'react'],
17
+ 'react-dom/client': ['ReactDOM', 'react-dom', 'react'],
18
+ 'react/jsx-runtime': ['ReactJSXRuntime', 'react-jsx-runtime', 'react'],
19
+ 'react/jsx-dev-runtime': ['ReactJSXRuntime', 'react-jsx-runtime', 'react'],
20
+ };
21
+
22
+ const bundledWordPressPackages = new Set(['admin-ui', 'dataviews', 'dataviews/wp', 'fields', 'global-styles-engine', 'global-styles-ui', 'grid', 'icons', 'interface', 'kebab-case', 'react-inert-value', 'style-runtime', 'sync', 'ui', 'undo-manager', 'views']);
23
+
24
+ function externalFor(request) {
25
+ if (Object.hasOwn(externals, request)) {
26
+ return externals[request];
27
+ }
28
+
29
+ if (/^(?:react|react-dom)\//.test(request) || request.includes('react-refresh/runtime')) {
30
+ throw new Error(`Unsupported React external: ${request}`);
31
+ }
32
+
33
+ if (!request.startsWith('@wordpress/')) {
34
+ return;
35
+ }
36
+
37
+ const name = request.slice('@wordpress/'.length);
38
+
39
+ if (bundledWordPressPackages.has(name)) {
40
+ return;
41
+ }
42
+
43
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
44
+ throw new Error(`Unsupported WordPress external: ${request}`);
45
+ }
46
+
47
+ return [['wp', name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())], `wp-${name}`, 'wordpress'];
48
+ }
49
+
50
+ async function coreExports(root, request) {
51
+ if (!root) {
52
+ throw new Error(`WordPress root is required to discover exports for ${request}`);
53
+ }
54
+
55
+ const name = request.slice('@wordpress/'.length);
56
+ const script = await readFile(resolve(root, 'wp-includes/js/dist', `${name}.js`), 'utf8');
57
+ const matches = [...script.matchAll(/__export\(index_exports, \{([\s\S]*?)\n\s*\}\);/g)];
58
+
59
+ if (matches.length !== 1 || !script.includes('return __toCommonJS(index_exports);')) {
60
+ throw new Error(`Cannot identify WordPress core exports for ${request}`);
61
+ }
62
+
63
+ const names = matches[0][1]
64
+ .trim()
65
+ .split(/,\s*\n/)
66
+ .map((entry) => entry.trim().match(/^([A-Za-z_$][\w$]*):\s*\(\)\s*=>\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/)?.[1]);
67
+
68
+ if (!names.length || names.some((name) => !name) || new Set(names).size !== names.length) {
69
+ throw new Error(`Cannot parse WordPress core exports for ${request}`);
70
+ }
71
+
72
+ return names;
73
+ }
74
+
75
+ /** Create a fresh adapter for each Bun build. Paths must be absolute. */
76
+ export function wordpressPlugin({ projectRoot = process.cwd(), wpRoot } = {}) {
77
+ if (!isAbsolute(projectRoot) || (wpRoot !== undefined && !isAbsolute(wpRoot))) {
78
+ throw new Error('projectRoot and wpRoot must be absolute paths');
79
+ }
80
+
81
+ const projectRequire = createRequire(resolve(projectRoot, 'package.json'));
82
+ const dependencies = new Set();
83
+ const modules = new Map();
84
+ const handles = new Map();
85
+
86
+ return {
87
+ dependencies,
88
+ getEmittedDependencies(metafile) {
89
+ try {
90
+ const data = typeof metafile === 'string' ? JSON.parse(metafile) : metafile;
91
+ const outputs = Object.values(data?.outputs ?? {});
92
+
93
+ if (!outputs.length) {
94
+ return [...dependencies].sort();
95
+ }
96
+
97
+ const emitted = new Set();
98
+
99
+ for (const output of outputs) {
100
+ if (!output?.inputs || typeof output.inputs !== 'object') {
101
+ return [...dependencies].sort();
102
+ }
103
+
104
+ for (const [input, info] of Object.entries(output.inputs)) {
105
+ if (!input.startsWith('wordpress-global:')) {
106
+ continue;
107
+ }
108
+
109
+ if (typeof info?.bytesInOutput !== 'number') {
110
+ return [...dependencies].sort();
111
+ }
112
+
113
+ if (!info.bytesInOutput) {
114
+ continue;
115
+ }
116
+
117
+ const key = input.slice('wordpress-global:'.length);
118
+
119
+ if (!handles.has(key)) {
120
+ return [...dependencies].sort();
121
+ }
122
+
123
+ emitted.add(handles.get(key));
124
+ }
125
+ }
126
+
127
+ return [...emitted].sort();
128
+ } catch {
129
+ return [...dependencies].sort();
130
+ }
131
+ },
132
+ plugin: allowPureJsxGrouping({
133
+ name: 'wordpress-globals',
134
+ setup(build) {
135
+ build.onResolve({ filter: /^(?:moment|jquery|lodash|lodash-es|@babel\/runtime\/regenerator|react|react-dom)(?:$|\/)|^@wordpress\/|react-refresh\/runtime/ }, async (args) => {
136
+ const request = args.path;
137
+ const external = externalFor(request);
138
+
139
+ if (!external) {
140
+ return;
141
+ }
142
+
143
+ const [global, handle, kind] = external;
144
+ const require = isAbsolute(args.importer) ? createRequire(args.importer) : projectRequire;
145
+ let metadata;
146
+ let entry;
147
+ let fallback = false;
148
+
149
+ if (kind === 'wordpress') {
150
+ try {
151
+ metadata = require(`${request}/package.json`);
152
+ } catch (error) {
153
+ if (error.code !== 'MODULE_NOT_FOUND' || !['@wordpress/plugins', '@wordpress/core-data'].includes(request)) {
154
+ throw error;
155
+ }
156
+
157
+ fallback = true;
158
+ }
159
+
160
+ if (!fallback && metadata.wpScript !== true) {
161
+ throw new Error(`Missing wpScript metadata: ${request}`);
162
+ }
163
+ }
164
+
165
+ if (kind !== 'commonjs' && kind !== 'wordpress') {
166
+ const importer = isAbsolute(args.importer) ? args.importer : resolve(projectRoot, '__wordpress_plugin__.mjs');
167
+
168
+ entry = kind === 'react' ? require.resolve(request) : Bun.resolveSync(request, dirname(importer));
169
+ }
170
+
171
+ const key = JSON.stringify([request, entry || '', fallback]);
172
+
173
+ if (!modules.has(key)) {
174
+ let names = [];
175
+
176
+ try {
177
+ if (kind === 'wordpress') {
178
+ names = await coreExports(wpRoot, request);
179
+ } else if (kind === 'react') {
180
+ names = ['default', ...Object.keys(require(entry)).filter((name) => name !== 'default')];
181
+ } else if (kind !== 'commonjs') {
182
+ const script = `const r = await Bun.build({ entrypoints: [process.argv[1]], target: 'browser', format: 'esm', write: false }); if (!r.success || r.outputs.length !== 1) { console.error(r.logs.join('\\n')); process.exit(1); } console.log(JSON.stringify(new Bun.Transpiler().scan(await r.outputs[0].text()).exports));`;
183
+ const result = await execFileAsync(process.execPath, ['-e', script, entry], { cwd: projectRoot, maxBuffer: 1024 * 1024 });
184
+
185
+ names = JSON.parse(result.stdout);
186
+ }
187
+ } catch (error) {
188
+ throw new Error(`Cannot determine exports for ${request}: ${error.message}`);
189
+ }
190
+
191
+ const path = Array.isArray(global) ? global : [global];
192
+ const lines = [`const value = ${path.reduce((expression, part) => `${expression}?.[${JSON.stringify(part)}]`, 'globalThis')};`, `if (value == null) throw new Error(${JSON.stringify(`Missing WordPress global for ${request}`)});`];
193
+
194
+ if (request === 'react/jsx-dev-runtime') {
195
+ lines.push("if (typeof value.jsx !== 'function') throw new Error('Missing ReactJSXRuntime.jsx');", 'module.exports = { Fragment: value.Fragment, jsxDEV: (type, props, key) => value.jsx(type, props, key) };');
196
+ } else if (kind === 'commonjs' || kind === 'react') {
197
+ lines.push('module.exports = value;');
198
+ } else {
199
+ for (const [index, name] of names.entries()) {
200
+ if (name === 'default') {
201
+ lines.push(kind === 'esm' || metadata?.wpScriptDefaultExport === true ? 'export default value;' : 'export default value.default;');
202
+ } else {
203
+ lines.push(`const export${index} = value[${JSON.stringify(name)}];`, `export { export${index} as ${name} };`);
204
+ }
205
+ }
206
+ }
207
+
208
+ modules.set(key, lines.join('\n'));
209
+ }
210
+
211
+ dependencies.add(handle);
212
+ handles.set(key, handle);
213
+
214
+ return { path: key, namespace: 'wordpress-global' };
215
+ });
216
+ build.onLoad({ filter: /.*/, namespace: 'wordpress-global' }, (args) => ({ contents: modules.get(args.path), loader: 'js' }));
217
+ },
218
+ }),
219
+ };
220
+ }