@eightshift/frontend-libs-tailwind 4.0.0-beta.4 → 4.0.0-beta.5

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.
@@ -5,6 +5,7 @@ let watcher;
5
5
  let drain;
6
6
  const stop = () => {
7
7
  stopping = true;
8
+
8
9
  if (watcher && !drain) {
9
10
  drain = Promise.resolve()
10
11
  .then(() => watcher.stop())
@@ -15,26 +16,42 @@ const stop = () => {
15
16
  .finally(() => process.disconnect?.());
16
17
  }
17
18
  };
19
+
18
20
  process.on('SIGINT', stop);
19
21
  process.on('SIGTERM', stop);
20
22
  process.on('message', (message) => {
21
- if (message === 'stop') stop();
23
+ if (message === 'stop') {
24
+ stop();
25
+ }
22
26
  });
23
27
  process.send('ready');
28
+
24
29
  try {
25
30
  const { command, config, options } = JSON.parse(process.argv[2]);
26
31
  const { default: definition } = await import(pathToFileURL(config).href);
32
+
27
33
  if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
28
34
  throw new TypeError('Config default export must be a defineBuild result');
29
35
  }
36
+
30
37
  if (!stopping) {
31
- if (command === 'build') await definition.build(options);
32
- else watcher = definition.watch(options);
38
+ if (command === 'build') {
39
+ await definition.build(options);
40
+ } else {
41
+ watcher = definition.watch(options);
42
+ }
43
+ } else if (command === 'build') {
44
+ process.exitCode = 1;
45
+ }
46
+
47
+ if (stopping) {
48
+ stop();
33
49
  }
34
- if (stopping) stop();
35
50
  } catch (error) {
36
51
  console.error(error);
37
52
  process.exitCode = 1;
38
53
  } finally {
39
- if (!watcher) process.disconnect?.();
54
+ if (!watcher) {
55
+ process.disconnect?.();
56
+ }
40
57
  }
package/bun/css.mjs CHANGED
@@ -1,22 +1,29 @@
1
- import { compile, Polyfills } from '@tailwindcss/node';
1
+ import { Features, loadModule, Polyfills } from '@tailwindcss/node';
2
+ import fs from 'node:fs';
2
3
  import { Scanner } from '@tailwindcss/oxide';
3
- import { createHash } from 'node:crypto';
4
+ import { createHash, randomUUID } from 'node:crypto';
4
5
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
6
  import { createRequire } from 'node:module';
6
- import { dirname, extname, relative, resolve } from 'node:path';
7
+ import { delimiter, dirname, extname, relative, resolve } from 'node:path';
7
8
  import browserslist from 'browserslist';
8
9
  import { browserslistToTargets, transform } from 'lightningcss';
9
10
  import postcss from 'postcss';
10
11
  import valueParser from 'postcss-value-parser';
11
12
 
12
13
  const require = createRequire(import.meta.url);
14
+ // Use the compiler and CSS resolver shipped with our Tailwind Node adapter.
15
+ const tailwindRequire = createRequire(require.resolve('@tailwindcss/node'));
16
+ const { compile } = tailwindRequire('tailwindcss');
17
+ const { CachedInputFileSystem, ResolverFactory } = tailwindRequire('enhanced-resolve');
13
18
 
14
19
  /**
15
20
  * Compile ordered stylesheets to one CSS file.
16
21
  * Paths are relative to projectDir unless absolute. Each files entry is a path
17
- * or { file, scan, sources, scanFiles, removeSources }; scan enables Tailwind
18
- * candidate scanning, sources extends its detected sources, scanFiles adds
19
- * explicit candidate files, and removeSources removes exact @source rules.
22
+ * or { file, content, scan, sources, scanFiles, removeSources }; content can
23
+ * replace the source text, while file remains the base for relative imports.
24
+ * scan enables candidate scanning, or 'auto' scans only when utilities are requested.
25
+ * sources extends detected sources, scanFiles adds explicit candidate files,
26
+ * and removeSources removes exact @source rules.
20
27
  * Assets are copied beside outputFile with content-hashed names.
21
28
  */
22
29
  export async function processCss({ projectDir, outputFile, files, production = false, browsers = '>= 0.25%' }) {
@@ -30,7 +37,9 @@ export async function processCss({ projectDir, outputFile, files, production = f
30
37
 
31
38
  await mkdir(outdir, { recursive: true });
32
39
 
33
- const rewriteAssets = async (css, base) => {
40
+ const assetReferences = new Map();
41
+ const assetPrefix = `eightshift-asset:${randomUUID()}:`;
42
+ const rewriteAssets = async (css, base, compiled = false) => {
34
43
  const tree = postcss.parse(css);
35
44
  const pending = [];
36
45
 
@@ -38,26 +47,37 @@ export async function processCss({ projectDir, outputFile, files, production = f
38
47
  const value = valueParser(declaration.value);
39
48
  const assets = [];
40
49
 
41
- value.walk((node) => {
42
- if (node.type !== 'function' || node.value.toLowerCase() !== 'url') {
50
+ const rewriteUrl = (node) => {
51
+ const reference = compiled ? assetReferences.get(node.value) : undefined;
52
+ const url = reference?.url ?? node.value;
53
+ const assetBase = reference?.base ?? base;
54
+
55
+ if (!url || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url)) {
43
56
  return;
44
57
  }
45
58
 
46
- const url = valueParser
47
- .stringify(node.nodes)
48
- .trim()
49
- .replace(/^(['"])(.*)\1$/, '$2');
59
+ if (!compiled) {
60
+ const token = `${assetPrefix}${assetReferences.size}`;
61
+ assetReferences.set(token, { url, base });
62
+ node.value = token;
50
63
 
51
- if (!url || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url)) {
52
64
  return;
53
65
  }
54
66
 
55
67
  assets.push(
56
68
  (async () => {
57
69
  const suffixIndex = url.search(/[?#]/);
58
- const pathname = suffixIndex < 0 ? url : url.slice(0, suffixIndex);
70
+ const encodedPathname = suffixIndex < 0 ? url : url.slice(0, suffixIndex);
59
71
  const suffix = suffixIndex < 0 ? '' : url.slice(suffixIndex);
60
- let asset = resolve(base, pathname);
72
+ let pathname;
73
+
74
+ try {
75
+ pathname = decodeURIComponent(encodedPathname);
76
+ } catch (cause) {
77
+ throw new Error(`Invalid percent encoding in CSS asset URL ${JSON.stringify(url)} relative to ${assetBase}`, { cause });
78
+ }
79
+
80
+ let asset = resolve(assetBase, pathname);
61
81
  let content;
62
82
 
63
83
  try {
@@ -67,16 +87,42 @@ export async function processCss({ projectDir, outputFile, files, production = f
67
87
  throw error;
68
88
  }
69
89
 
70
- asset = require.resolve(pathname, { paths: [base] });
90
+ asset = require.resolve(pathname, { paths: [assetBase] });
71
91
  content = await readFile(asset);
72
92
  }
73
93
 
74
94
  const name = `${createHash('sha256').update(content).digest('hex').slice(0, 20)}${extname(asset)}`;
75
95
 
76
96
  await writeFile(resolve(outdir, name), content);
77
- node.nodes = [{ type: 'string', quote: '"', value: `./${name}${suffix}` }];
97
+ node.type = 'string';
98
+ node.quote ??= '"';
99
+ node.value = `./${name}${suffix}`;
100
+ dependencies.add(asset);
78
101
  })(),
79
102
  );
103
+ };
104
+
105
+ value.walk((node) => {
106
+ if (node.type !== 'function') {
107
+ return;
108
+ }
109
+
110
+ const name = node.value.toLowerCase();
111
+
112
+ if (name === 'url') {
113
+ const url = node.nodes.filter((child) => child.type !== 'space' && child.type !== 'comment');
114
+
115
+ if (url.length === 1 && (url[0].type === 'string' || url[0].type === 'word')) {
116
+ rewriteUrl(url[0]);
117
+ }
118
+
119
+ return false;
120
+ }
121
+
122
+ if (name === 'image-set' || name === '-webkit-image-set') {
123
+ // Only direct strings are images; nested type("image/avif") is a descriptor.
124
+ node.nodes.filter((child) => child.type === 'string').forEach((child) => rewriteUrl(child));
125
+ }
80
126
  });
81
127
  pending.push(
82
128
  Promise.all(assets).then(() => {
@@ -91,6 +137,30 @@ export async function processCss({ projectDir, outputFile, files, production = f
91
137
 
92
138
  const parts = [];
93
139
  const dependencies = new Set();
140
+ const cssResolver = ResolverFactory.createResolver({
141
+ fileSystem: new CachedInputFileSystem(fs, 4000),
142
+ extensions: ['.css'],
143
+ mainFields: ['style'],
144
+ conditionNames: ['style'],
145
+ modules: ['node_modules', ...(process.env.NODE_PATH ? process.env.NODE_PATH.split(delimiter) : [])],
146
+ });
147
+ const loadStylesheet = async (id, base) => {
148
+ const path = await new Promise((accept, reject) => {
149
+ cssResolver.resolve({}, base, id, {}, (error, result) => {
150
+ if (error) {
151
+ reject(error);
152
+ } else if (!result) {
153
+ reject(new Error(`Could not resolve '${id}' from '${base}'`));
154
+ } else {
155
+ accept(result);
156
+ }
157
+ });
158
+ });
159
+ dependencies.add(path);
160
+
161
+ // Retain each URL's source base through compilation; copy only emitted assets.
162
+ return { path, base: dirname(path), content: await rewriteAssets(await readFile(path, 'utf8'), dirname(path)) };
163
+ };
94
164
 
95
165
  for (const entry of files) {
96
166
  const options = typeof entry === 'string' ? { file: entry } : entry;
@@ -99,8 +169,12 @@ export async function processCss({ projectDir, outputFile, files, production = f
99
169
  throw new Error('Each CSS entry requires a file path.');
100
170
  }
101
171
 
172
+ if (options.content !== undefined && typeof options.content !== 'string') {
173
+ throw new TypeError('CSS entry content must be a string.');
174
+ }
175
+
102
176
  const file = resolve(root, options.file);
103
- let input = await readFile(file, 'utf8');
177
+ let input = options.content ?? (await readFile(file, 'utf8'));
104
178
 
105
179
  dependencies.add(file);
106
180
 
@@ -112,16 +186,40 @@ export async function processCss({ projectDir, outputFile, files, production = f
112
186
  input = input.replace(source, '');
113
187
  }
114
188
 
115
- const compiler = await compile(input, {
189
+ const compiler = await compile(await rewriteAssets(input, dirname(file)), {
116
190
  base: dirname(file),
117
191
  from: file,
118
- shouldRewriteUrls: true,
119
192
  polyfills: Polyfills.All,
120
- onDependency: (dependency) => dependencies.add(dependency),
193
+ loadStylesheet,
194
+ loadModule: (id, base) => loadModule(id, base, (dependency) => dependencies.add(dependency)),
121
195
  });
196
+
197
+ if (compiler.root && compiler.root !== 'none') {
198
+ const directoryParts = [];
199
+
200
+ for (const part of compiler.root.pattern.split('/')) {
201
+ if (/[*{]/.test(part)) {
202
+ break;
203
+ }
204
+
205
+ directoryParts.push(part);
206
+ }
207
+
208
+ const directory = directoryParts.join('/');
209
+
210
+ if (
211
+ !(await fs.promises
212
+ .stat(resolve(compiler.root.base, directory))
213
+ .then((stat) => stat.isDirectory())
214
+ .catch(() => false))
215
+ ) {
216
+ throw new Error(`The \`source(${compiler.root.pattern})\` does not exist or is not a directory.`);
217
+ }
218
+ }
219
+
122
220
  let candidates = [];
123
221
 
124
- if (options.scan) {
222
+ if (options.scan && (options.scan !== 'auto' || compiler.features & Features.Utilities)) {
125
223
  const sources = (compiler.root === 'none' ? [] : compiler.root === null ? [{ base: root, pattern: '**/*', negated: false }] : [{ ...compiler.root, negated: false }]).concat(
126
224
  compiler.sources,
127
225
  (options.sources ?? []).map((source) => ({ ...source, base: resolve(root, source.base ?? '.') })),
@@ -130,10 +228,13 @@ export async function processCss({ projectDir, outputFile, files, production = f
130
228
  const explicit = (options.scanFiles ?? []).map((item) => (typeof item === 'string' ? { file: resolve(root, item), extension: extname(item).slice(1) } : { ...item, file: resolve(root, item.file) }));
131
229
 
132
230
  explicit.forEach(({ file: candidateFile }) => dependencies.add(candidateFile));
133
- candidates = [...new Set([...scanner.scan(), ...(explicit.length ? scanner.scanFiles(explicit) : [])])];
231
+ const explicitContents = await Promise.all(explicit.map(async ({ file: candidateFile, extension }) => ({ content: await readFile(candidateFile, 'utf8'), extension })));
232
+ const explicitCandidates = explicitContents.length ? new Scanner({ sources: [] }).scanFiles(explicitContents) : [];
233
+ candidates = [...new Set([...scanner.scan(), ...explicitCandidates])];
134
234
  }
135
235
 
136
- parts.push(`/* ${relative(root, file)} */\n${await rewriteAssets(compiler.build(candidates), dirname(file))}`);
236
+ const compiled = compiler.build(candidates);
237
+ parts.push(`/* ${relative(root, file)} */\n${await rewriteAssets(compiled, dirname(file), true)}`);
137
238
  }
138
239
 
139
240
  const css = parts.join('\n');
package/bun/discovery.mjs CHANGED
@@ -12,6 +12,7 @@ import { dirname, relative, resolve, sep } from 'node:path';
12
12
  * to an empty object. JSON contexts return parsed values; other synchronous
13
13
  * imports return module namespaces. Regenerate after changing source files.
14
14
  * Symlinks are skipped. Missing directories are treated as empty contexts.
15
+ * Names cannot shadow the generated helpers or Map, Promise and Error.
15
16
  */
16
17
  export async function generateDiscovery({ root, output, definitions }) {
17
18
  if (typeof root !== 'string' || typeof output !== 'string' || !Array.isArray(definitions)) {
@@ -29,7 +30,17 @@ export async function generateDiscovery({ root, output, definitions }) {
29
30
  for (const definition of definitions) {
30
31
  const { name, directory, pattern, mode = 'sync' } = definition;
31
32
 
32
- if (typeof name !== 'string' || !/^[$A-Z_a-z][$\w]*$/.test(name) || !isValidExportName(name) || name === 'createContext' || /^module\d+$/.test(name) || names.has(name) || typeof directory !== 'string' || !(pattern instanceof RegExp) || !['sync', 'lazy'].includes(mode)) {
33
+ if (
34
+ typeof name !== 'string' ||
35
+ !/^[$A-Z_a-z][$\w]*$/.test(name) ||
36
+ !isValidExportName(name) ||
37
+ ['createContext', 'Map', 'Promise', 'Error'].includes(name) ||
38
+ /^module\d+$/.test(name) ||
39
+ names.has(name) ||
40
+ typeof directory !== 'string' ||
41
+ !(pattern instanceof RegExp) ||
42
+ !['sync', 'lazy'].includes(mode)
43
+ ) {
33
44
  throw new TypeError('Invalid or duplicate discovery definition');
34
45
  }
35
46
 
@@ -6,12 +6,14 @@ import { supportsPureJsxGrouping } from './plugin-capabilities.mjs';
6
6
  const removePassDirectory = async (directory) => {
7
7
  for (const item of await readdir(directory, { withFileTypes: true })) {
8
8
  const path = resolve(directory, item.name);
9
+
9
10
  if (item.isDirectory()) {
10
11
  await removePassDirectory(path);
11
12
  } else {
12
13
  await unlink(path);
13
14
  }
14
15
  }
16
+
15
17
  await rmdir(directory);
16
18
  };
17
19
 
@@ -22,17 +24,22 @@ export async function buildNativeEditorChunks(options) {
22
24
  // Some Bun versions write outdir despite write:false. Never expose discarded passes.
23
25
  const privateDirectory = resolve(dirname(directory), `.eightshift-native-${randomUUID()}`);
24
26
  await mkdir(privateDirectory);
27
+
25
28
  try {
26
29
  const result = await compileNativeEditorChunks({ ...options, directory: privateDirectory, scriptDirectory: directory });
27
30
  const mapPath = (path) => {
28
31
  const location = relative(privateDirectory, path);
32
+
29
33
  if (!location || isAbsolute(location) || location === '..' || location.startsWith(`..${sep}`)) {
30
34
  throw new Error(`Native editor output escapes its private directory: ${path}`);
31
35
  }
36
+
32
37
  return resolve(directory, location);
33
38
  };
39
+
34
40
  const outputs = [];
35
41
  const byPath = new Map();
42
+
36
43
  for (const output of result.outputs) {
37
44
  // Materialize before cleanup: a BuildArtifact may be backed by its emitted file.
38
45
  const bytes = await output.arrayBuffer();
@@ -41,19 +48,24 @@ export async function buildNativeEditorChunks(options) {
41
48
  outputs.push(artifact);
42
49
  byPath.set(output.path, artifact);
43
50
  }
51
+
44
52
  for (const [index, output] of result.outputs.entries()) {
45
53
  if (output.sourcemap) {
46
54
  const map = byPath.get(output.sourcemap.path);
55
+
47
56
  if (!map) {
48
57
  throw new Error('Missing native editor source map artifact');
49
58
  }
59
+
50
60
  outputs[index].sourcemap = map;
51
61
  }
52
62
  }
63
+
53
64
  const metafile = {
54
65
  ...result.metafile,
55
66
  outputs: Object.fromEntries(Object.entries(result.metafile.outputs).map(([path, info]) => [mapPath(resolve(privateDirectory, path)), { ...info, imports: info.imports?.map((item) => ({ ...item, path: isAbsolute(item.path) && !item.external ? mapPath(item.path) : item.path })) }])),
56
67
  };
68
+
57
69
  return { ...result, outputs, metafile };
58
70
  } finally {
59
71
  await removePassDirectory(privateDirectory);
@@ -62,6 +74,7 @@ export async function buildNativeEditorChunks(options) {
62
74
 
63
75
  async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, entryOutput, scriptUrlIdentifier, buildOptions, plugins, pureJsxGroups = false }) {
64
76
  let entryPath = relative(scriptDirectory, entryOutput).split(sep).join('/');
77
+
65
78
  if (!entryPath.startsWith('.')) {
66
79
  entryPath = `./${entryPath}`;
67
80
  }
@@ -88,21 +101,26 @@ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, e
88
101
 
89
102
  const readMetadata = (build) => {
90
103
  let metadata;
104
+
91
105
  try {
92
106
  metadata = typeof build.metafile === 'string' ? JSON.parse(build.metafile) : build.metafile;
107
+
93
108
  if (!metadata?.outputs || typeof metadata.outputs !== 'object') {
94
109
  throw new Error('Missing output metadata');
95
110
  }
96
111
  } catch (cause) {
97
112
  throw new Error('Cannot map native editor entries: Bun returned unreadable build metadata', { cause });
98
113
  }
114
+
99
115
  if (!metadata.inputs || typeof metadata.inputs !== 'object') {
100
116
  throw new Error('Cannot verify native editor dynamic imports: missing input metadata');
101
117
  }
118
+
102
119
  for (const [source, info] of Object.entries(metadata.inputs)) {
103
120
  if (!Array.isArray(info?.imports)) {
104
121
  throw new Error(`Cannot verify native editor dynamic imports in ${source}`);
105
122
  }
123
+
106
124
  // Inlined dynamic imports can return plain objects or broken self-import helpers.
107
125
  for (const imported of info.imports) {
108
126
  if (imported.kind === 'dynamic-import' && !imported.external) {
@@ -110,12 +128,16 @@ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, e
110
128
  }
111
129
  }
112
130
  }
131
+
113
132
  return metadata;
114
133
  };
134
+
115
135
  let metadata = readMetadata(result);
116
136
  let grouping;
137
+
117
138
  if (pureJsxGroups) {
118
139
  let reason;
140
+
119
141
  if (options.sourcemap && options.sourcemap !== 'none') {
120
142
  reason = 'source maps require original ungrouped sources';
121
143
  } else if (plugins.some((plugin) => !supportsPureJsxGrouping(plugin))) {
@@ -125,16 +147,20 @@ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, e
125
147
  } else if (buildOptions.define?.['process.env.NODE_ENV'] !== '"production"') {
126
148
  reason = 'only the standard production JSX runtime is supported';
127
149
  }
150
+
128
151
  if (!reason) {
129
152
  try {
130
153
  const { createPureJsxGroups } = await import('./editor-pure-jsx.mjs');
131
154
  const plan = await createPureJsxGroups({ result, metadata, directory, entries: chunks, maxBytes: pureJsxGroups.maxBytes });
132
155
  grouping = plan.summary;
156
+
133
157
  if (plan.groups.length) {
134
158
  const grouped = await Bun.build({ ...options, plugins: [plan.plugin, ...plugins] });
159
+
135
160
  if (!grouped.success) {
136
161
  throw new AggregateError(grouped.logs, 'Grouped native editor compilation failed');
137
162
  }
163
+
138
164
  const groupedMetadata = readMetadata(grouped);
139
165
  await plan.verify(groupedMetadata, grouped);
140
166
  result = grouped;
@@ -144,6 +170,7 @@ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, e
144
170
  reason = error.message;
145
171
  }
146
172
  }
173
+
147
174
  if (reason) {
148
175
  console.warn(`[eightshift] Pure JSX grouping disabled: ${reason}. Using the ungrouped native build.`);
149
176
  grouping = { maxBytes: pureJsxGroups.maxBytes, groups: [], disabled: reason };
@@ -151,34 +178,45 @@ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, e
151
178
  }
152
179
 
153
180
  const outputPaths = new Set();
181
+
154
182
  for (const output of result.outputs) {
155
183
  const location = relative(directory, output.path);
184
+
156
185
  if (!location || isAbsolute(location) || location === '..' || location.startsWith(`..${sep}`)) {
157
186
  throw new Error(`Native editor output escapes its directory: ${output.path}`);
158
187
  }
188
+
159
189
  if (!['entry-point', 'chunk', 'sourcemap'].includes(output.kind) || !/\.js(?:\.map)?$/.test(location)) {
160
190
  throw new Error(`Unexpected native editor asset: ${output.path}`);
161
191
  }
192
+
162
193
  if (outputPaths.has(output.path)) {
163
194
  throw new Error(`Duplicate native editor output: ${output.path}`);
164
195
  }
196
+
165
197
  outputPaths.add(output.path);
166
198
  }
167
199
 
168
200
  const names = new Map();
169
201
  const entries = new Set();
202
+
170
203
  for (const [file, info] of Object.entries(metadata.outputs)) {
171
204
  if (!info.entryPoint) {
172
205
  continue;
173
206
  }
207
+
174
208
  const target = resolve(info.entryPoint);
209
+
175
210
  if (!chunks.has(target)) {
176
211
  continue;
177
212
  }
213
+
178
214
  const output = resolve(directory, file);
215
+
179
216
  if (!outputPaths.has(output) || entries.has(output)) {
180
217
  throw new Error(`Missing or ambiguous native editor entry: ${target}`);
181
218
  }
219
+
182
220
  entries.add(output);
183
221
  names.set(target, relative(directory, output).split(sep).join('/'));
184
222
  }