@quilted/rollup 0.1.1 → 0.1.3

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.
@@ -1,19 +1,28 @@
1
+ import * as path from 'node:path';
1
2
  import { MAGIC_MODULE_APP_COMPONENT, MAGIC_MODULE_REQUEST_ROUTER, MAGIC_MODULE_BROWSER_ASSETS, MAGIC_MODULE_ENTRY } from './constants.esnext';
2
3
  import { multiline } from './shared/strings.esnext';
4
+ import { rollupPluginsToArray, getNodePlugins } from './shared/rollup.esnext';
3
5
  import { createMagicModulePlugin } from './shared/magic-module.esnext';
4
6
 
5
- function quiltApp({
7
+ function quiltAppBrowser({
8
+ app,
6
9
  env,
7
- entry
10
+ assets,
11
+ module,
12
+ graphql = true
8
13
  } = {}) {
9
14
  return {
10
- name: '@quilted/app',
15
+ name: '@quilted/app/browser',
11
16
  async options(originalOptions) {
12
- const newPlugins = [...(Array.isArray(originalOptions.plugins) ? originalOptions.plugins : originalOptions.plugins ? [originalOptions.plugins] : [])];
17
+ const newPlugins = rollupPluginsToArray(originalOptions.plugins);
13
18
  const newOptions = {
14
19
  ...originalOptions,
15
20
  plugins: newPlugins
16
21
  };
22
+ const [{
23
+ visualizer
24
+ }, nodePlugins] = await Promise.all([import('rollup-plugin-visualizer'), getNodePlugins()]);
25
+ newPlugins.push(...nodePlugins);
17
26
  if (env) {
18
27
  const {
19
28
  magicModuleEnv,
@@ -36,44 +45,116 @@ function quiltApp({
36
45
  }));
37
46
  }
38
47
  }
39
- if (entry) {
48
+ if (app) {
40
49
  newPlugins.push(magicModuleAppComponent({
41
- entry
50
+ entry: app
42
51
  }));
43
52
  }
53
+ newPlugins.push(magicModuleAppBrowserEntry(module));
54
+ if (graphql) {
55
+ const {
56
+ graphql
57
+ } = await import('./graphql.esnext');
58
+ newPlugins.push(graphql({
59
+ manifest: path.resolve(`manifests/graphql.json`)
60
+ }));
61
+ }
62
+ const minify = assets?.minify ?? true;
63
+ if (minify) {
64
+ const {
65
+ minify
66
+ } = await import('rollup-plugin-esbuild');
67
+ newPlugins.push(minify());
68
+ }
69
+ newPlugins.push(visualizer({
70
+ template: 'treemap',
71
+ open: false,
72
+ brotliSize: true,
73
+ filename: path.resolve(`reports/bundle-visualizer.html`)
74
+ }));
44
75
  return newOptions;
45
- }
46
- };
47
- }
48
- function quiltAppBrowser(options = {}) {
49
- return {
50
- name: '@quilted/app/browser',
51
- options(originalOptions) {
52
- const newPlugins = [...(Array.isArray(originalOptions.plugins) ? originalOptions.plugins : originalOptions.plugins ? [originalOptions.plugins] : [])];
53
- const newOptions = {
76
+ },
77
+ outputOptions(originalOptions) {
78
+ return {
54
79
  ...originalOptions,
55
- plugins: newPlugins
80
+ // format: isESM ? 'esm' : 'systemjs',
81
+ format: 'esm',
82
+ dir: path.resolve(`build/assets`),
83
+ entryFileNames: `app.[hash].js`,
84
+ assetFileNames: `[name].[hash].[ext]`,
85
+ chunkFileNames: `[name].[hash].js`,
86
+ manualChunks: createManualChunksSorter()
56
87
  };
57
- newPlugins.push(magicModuleAppBrowserEntry(options));
58
- return newOptions;
59
88
  }
60
89
  };
61
90
  }
62
- function quiltAppServer(options = {}) {
91
+ function quiltAppServer({
92
+ app,
93
+ env,
94
+ graphql,
95
+ entry
96
+ } = {}) {
63
97
  return {
64
98
  name: '@quilted/app/server',
65
99
  async options(originalOptions) {
66
- const newPlugins = [...(Array.isArray(originalOptions.plugins) ? originalOptions.plugins : originalOptions.plugins ? [originalOptions.plugins] : [])];
67
- const [{
68
- magicModuleRequestRouterEntry
69
- }] = await Promise.all([import('./request-router.esnext')]);
100
+ const newPlugins = rollupPluginsToArray(originalOptions.plugins);
70
101
  const newOptions = {
71
102
  ...originalOptions,
72
103
  plugins: newPlugins
73
104
  };
105
+ const [{
106
+ magicModuleRequestRouterEntry
107
+ }, nodePlugins] = await Promise.all([import('./request-router.esnext'), getNodePlugins()]);
108
+ newPlugins.push(...nodePlugins);
109
+ if (env) {
110
+ const {
111
+ magicModuleEnv,
112
+ replaceProcessEnv
113
+ } = await import('./env.esnext');
114
+ if (typeof env === 'boolean') {
115
+ newPlugins.push(replaceProcessEnv({
116
+ mode: 'production'
117
+ }));
118
+ newPlugins.push(magicModuleEnv({
119
+ mode: 'production'
120
+ }));
121
+ } else {
122
+ newPlugins.push(replaceProcessEnv({
123
+ mode: env.mode ?? 'production'
124
+ }));
125
+ newPlugins.push(magicModuleEnv({
126
+ mode: 'production',
127
+ ...env
128
+ }));
129
+ }
130
+ }
131
+ if (app) {
132
+ newPlugins.push(magicModuleAppComponent({
133
+ entry: app
134
+ }));
135
+ }
74
136
  newPlugins.push(magicModuleRequestRouterEntry());
75
- newPlugins.push(magicModuleAppRequestRouter(options));
137
+ newPlugins.push(magicModuleAppRequestRouter({
138
+ entry
139
+ }));
140
+ if (graphql) {
141
+ const {
142
+ graphql
143
+ } = await import('./graphql.esnext');
144
+ newPlugins.push(graphql({
145
+ manifest: false
146
+ }));
147
+ }
76
148
  return newOptions;
149
+ },
150
+ outputOptions(originalOptions) {
151
+ return {
152
+ ...originalOptions,
153
+ // format,
154
+ format: 'esm',
155
+ dir: path.resolve(`build/server`),
156
+ entryFileNames: 'server.js'
157
+ };
77
158
  }
78
159
  };
79
160
  }
@@ -147,5 +228,71 @@ function magicModuleAppBrowserEntry({
147
228
  }
148
229
  });
149
230
  }
231
+ const FRAMEWORK_CHUNK_NAME = 'framework';
232
+ const POLYFILLS_CHUNK_NAME = 'polyfills';
233
+ const VENDOR_CHUNK_NAME = 'vendor';
234
+ const INTERNALS_CHUNK_NAME = 'internals';
235
+ const SHARED_CHUNK_NAME = 'shared';
236
+ const PACKAGES_CHUNK_NAME = 'packages';
237
+ const GLOBAL_CHUNK_NAME = 'global';
238
+ const FRAMEWORK_TEST_STRINGS = ['/node_modules/preact/', '/node_modules/react/', '/node_modules/js-cookie/', '/node_modules/@quilted/quilt/', '/node_modules/@preact/signals/', '/node_modules/@preact/signals-core/',
239
+ // TODO I should turn this into an allowlist
240
+ /node_modules[/]@quilted[/](?!react-query|swr)/];
241
+ const POLYFILL_TEST_STRINGS = ['/node_modules/@quilted/polyfills/', '/node_modules/core-js/', '/node_modules/whatwg-fetch/', '/node_modules/regenerator-runtime/', '/node_modules/abort-controller/'];
242
+ const INTERNALS_TEST_STRINGS = ['\x00commonjsHelpers.js', '/node_modules/@babel/runtime/'];
243
+
244
+ // When building from source, quilt packages are not in node_modules,
245
+ // so we instead add their repo paths to the list of framework test strings.
246
+ if (process.env.QUILT_FROM_SOURCE) {
247
+ FRAMEWORK_TEST_STRINGS.push('/quilt/packages/');
248
+ }
249
+
250
+ // Inspired by Vite: https://github.com/vitejs/vite/blob/c69f83615292953d40f07b1178d1ed1d72abe695/packages/vite/source/node/build.ts#L567
251
+ function createManualChunksSorter() {
252
+ // TODO: make this more configurable, and make it so that we bundle more intelligently
253
+ // for split entries
254
+ const packagesPath = path.resolve('packages') + path.sep;
255
+ const globalPath = path.resolve('global') + path.sep;
256
+ const sharedPath = path.resolve('shared') + path.sep;
257
+ return (id, {
258
+ getModuleInfo
259
+ }) => {
260
+ if (INTERNALS_TEST_STRINGS.some(test => id.includes(test))) {
261
+ return INTERNALS_CHUNK_NAME;
262
+ }
263
+ if (FRAMEWORK_TEST_STRINGS.some(test => typeof test === 'string' ? id.includes(test) : test.test(id))) {
264
+ return FRAMEWORK_CHUNK_NAME;
265
+ }
266
+ if (POLYFILL_TEST_STRINGS.some(test => id.includes(test))) {
267
+ return POLYFILLS_CHUNK_NAME;
268
+ }
269
+ let bundleBaseName;
270
+ let relativeId;
271
+ if (id.includes('/node_modules/')) {
272
+ const moduleInfo = getModuleInfo(id);
273
+
274
+ // If the only dependency is another vendor, let Rollup handle the naming
275
+ if (moduleInfo == null) return;
276
+ if (moduleInfo.importers.length > 0 && moduleInfo.importers.every(importer => importer.includes('/node_modules/'))) {
277
+ return;
278
+ }
279
+ bundleBaseName = VENDOR_CHUNK_NAME;
280
+ relativeId = id.replace(/^.*[/]node_modules[/]/, '');
281
+ } else if (id.startsWith(packagesPath)) {
282
+ bundleBaseName = PACKAGES_CHUNK_NAME;
283
+ relativeId = id.replace(packagesPath, '');
284
+ } else if (id.startsWith(globalPath)) {
285
+ bundleBaseName = GLOBAL_CHUNK_NAME;
286
+ relativeId = id.replace(globalPath, '');
287
+ } else if (id.startsWith(sharedPath)) {
288
+ bundleBaseName = SHARED_CHUNK_NAME;
289
+ relativeId = id.replace(sharedPath, '');
290
+ }
291
+ if (bundleBaseName == null || relativeId == null) {
292
+ return;
293
+ }
294
+ return `${bundleBaseName}-${relativeId.split(path.sep)[0]?.split('.')[0]}`;
295
+ };
296
+ }
150
297
 
151
- export { magicModuleAppBrowserEntry, magicModuleAppComponent, magicModuleAppRequestRouter, quiltApp, quiltAppBrowser, quiltAppServer };
298
+ export { magicModuleAppBrowserEntry, magicModuleAppComponent, magicModuleAppRequestRouter, quiltAppBrowser, quiltAppServer };
@@ -0,0 +1,181 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { print, parse } from 'graphql';
3
+
4
+ const IMPORT_REGEX = /^#import\s+['"]([^'"]*)['"];?[\s\n]*/gm;
5
+ const DEFAULT_NAME = 'Operation';
6
+ function cleanGraphQLDocument(document, {
7
+ removeUnused = true
8
+ } = {}) {
9
+ if (removeUnused) {
10
+ removeUnusedDefinitions(document, {
11
+ exclude: removeUnused === true ? new Set() : removeUnused.exclude
12
+ });
13
+ }
14
+ for (const definition of document.definitions) {
15
+ addTypename(definition);
16
+ }
17
+ const normalizedSource = minifyGraphQLSource(print(document));
18
+ const normalizedDocument = parse(normalizedSource);
19
+ for (const definition of normalizedDocument.definitions) {
20
+ stripLoc(definition);
21
+ }
22
+
23
+ // This ID is a hash of the full file contents that are part of the document,
24
+ // including other documents that are injected in, but excluding any unused
25
+ // fragments. This is useful for things like persisted queries.
26
+ const id = createHash('sha256').update(normalizedSource).digest('hex');
27
+ Reflect.defineProperty(normalizedDocument, 'id', {
28
+ value: id,
29
+ enumerable: true,
30
+ writable: false,
31
+ configurable: false
32
+ });
33
+ Reflect.defineProperty(normalizedDocument, 'loc', {
34
+ value: stripDocumentLoc(normalizedDocument.loc),
35
+ enumerable: true,
36
+ writable: false,
37
+ configurable: false
38
+ });
39
+ return normalizedDocument;
40
+ }
41
+ function extractGraphQLImports(rawSource) {
42
+ const imports = new Set();
43
+ const source = rawSource.replace(IMPORT_REGEX, (_, imported) => {
44
+ imports.add(imported);
45
+ return '';
46
+ });
47
+ return {
48
+ imports: [...imports],
49
+ source
50
+ };
51
+ }
52
+ function toGraphQLOperation(documentOrSource) {
53
+ const document = typeof documentOrSource === 'string' ? cleanGraphQLDocument(parse(documentOrSource)) : documentOrSource;
54
+ return {
55
+ id: document.id,
56
+ name: operationNameForDocument(document),
57
+ source: document.loc.source.body
58
+ };
59
+ }
60
+ function operationNameForDocument(document) {
61
+ return document.definitions.find(definition => definition.kind === 'OperationDefinition')?.name?.value;
62
+ }
63
+ function removeUnusedDefinitions(document, {
64
+ exclude
65
+ }) {
66
+ const usedDefinitions = new Set();
67
+ const dependencies = definitionDependencies(document.definitions);
68
+ const markAsUsed = definition => {
69
+ if (usedDefinitions.has(definition)) {
70
+ return;
71
+ }
72
+ usedDefinitions.add(definition);
73
+ for (const dependency of dependencies.get(definition) || []) {
74
+ markAsUsed(dependency);
75
+ }
76
+ };
77
+ for (const definition of document.definitions) {
78
+ if (definition.kind === 'FragmentDefinition') {
79
+ if (exclude.has(definition.name.value)) {
80
+ markAsUsed(definition);
81
+ }
82
+ } else {
83
+ markAsUsed(definition);
84
+ }
85
+ }
86
+ document.definitions = [...usedDefinitions];
87
+ }
88
+ function definitionDependencies(definitions) {
89
+ const executableDefinitions = definitions.filter(definition => definition.kind === 'OperationDefinition' || definition.kind === 'FragmentDefinition');
90
+ const definitionsByName = new Map(executableDefinitions.map(definition => [definition.name ? definition.name.value : DEFAULT_NAME, definition]));
91
+ return new Map(executableDefinitions.map(executableNode => [executableNode, [...collectUsedFragmentSpreads(executableNode, new Set())].map(usedFragment => {
92
+ const definition = definitionsByName.get(usedFragment);
93
+ if (definition == null) {
94
+ throw new Error(`You attempted to use the fragment '${usedFragment}' (in '${executableNode.name ? executableNode.name.value : DEFAULT_NAME}'), but it does not exist. Maybe you forgot to import it from another document?`);
95
+ }
96
+ return definition;
97
+ })]));
98
+ }
99
+ const TYPENAME_FIELD = {
100
+ kind: 'Field',
101
+ alias: null,
102
+ name: {
103
+ kind: 'Name',
104
+ value: '__typename'
105
+ }
106
+ };
107
+ function addTypename(definition) {
108
+ for (const {
109
+ selections
110
+ } of selectionSetsForDefinition(definition)) {
111
+ const hasTypename = selections.some(selection => selection.kind === 'Field' && selection.name.value === '__typename');
112
+ if (!hasTypename) {
113
+ selections.push(TYPENAME_FIELD);
114
+ }
115
+ }
116
+ }
117
+ function collectUsedFragmentSpreads(definition, usedSpreads) {
118
+ for (const selection of selectionsForDefinition(definition)) {
119
+ if (selection.kind === 'FragmentSpread') {
120
+ usedSpreads.add(selection.name.value);
121
+ }
122
+ }
123
+ return usedSpreads;
124
+ }
125
+ function selectionsForDefinition(definition) {
126
+ if (!('selectionSet' in definition) || definition.selectionSet == null) {
127
+ return [][Symbol.iterator]();
128
+ }
129
+ return selectionsForSelectionSet(definition.selectionSet);
130
+ }
131
+ function* selectionSetsForDefinition(definition) {
132
+ if (!('selectionSet' in definition) || definition.selectionSet == null) {
133
+ return [][Symbol.iterator]();
134
+ }
135
+ if (definition.kind !== 'OperationDefinition') {
136
+ yield definition.selectionSet;
137
+ }
138
+ for (const nestedSelection of selectionsForDefinition(definition)) {
139
+ if ('selectionSet' in nestedSelection && nestedSelection.selectionSet != null) {
140
+ yield nestedSelection.selectionSet;
141
+ }
142
+ }
143
+ }
144
+ function* selectionsForSelectionSet({
145
+ selections
146
+ }) {
147
+ for (const selection of selections) {
148
+ yield selection;
149
+ if ('selectionSet' in selection && selection.selectionSet != null) {
150
+ yield* selectionsForSelectionSet(selection.selectionSet);
151
+ }
152
+ }
153
+ }
154
+ function stripDocumentLoc(loc) {
155
+ const normalizedLoc = {
156
+ ...loc
157
+ };
158
+ delete normalizedLoc.endToken;
159
+ delete normalizedLoc.startToken;
160
+ return normalizedLoc;
161
+ }
162
+ function stripLoc(value) {
163
+ if (Array.isArray(value)) {
164
+ value.forEach(stripLoc);
165
+ } else if (typeof value === 'object') {
166
+ if (value == null) {
167
+ return;
168
+ }
169
+ if ('loc' in value) {
170
+ delete value.loc;
171
+ }
172
+ for (const key of Object.keys(value)) {
173
+ stripLoc(value[key]);
174
+ }
175
+ }
176
+ }
177
+ function minifyGraphQLSource(source) {
178
+ return source.replace(/#.*/g, '').replace(/\\n/g, ' ').replace(/\s\s+/g, ' ').replace(/\s*({|}|\(|\)|\.|:|,)\s*/g, '$1');
179
+ }
180
+
181
+ export { cleanGraphQLDocument, extractGraphQLImports, minifyGraphQLSource, toGraphQLOperation };
@@ -0,0 +1,84 @@
1
+ import { dirname } from 'node:path';
2
+ import { mkdir, writeFile, readFile } from 'node:fs/promises';
3
+ import { parse } from 'graphql';
4
+ import { toGraphQLOperation, cleanGraphQLDocument, extractGraphQLImports } from './graphql/transform.esnext';
5
+
6
+ function graphql({
7
+ manifest
8
+ } = {}) {
9
+ const shouldWriteManifest = Boolean(manifest);
10
+ const manifestPath = typeof manifest === 'string' ? manifest : `manifests/graphql.json`;
11
+ return {
12
+ name: '@quilted/graphql',
13
+ async transform(code, id) {
14
+ if (!id.endsWith('.graphql') && !id.endsWith('.gql')) return null;
15
+ const topLevelDefinitions = new Set();
16
+ const loadedDocument = await loadDocument(code, id, this, (document, level) => {
17
+ if (level !== 0) return;
18
+ for (const definition of document.definitions) {
19
+ if ('name' in definition && definition.name != null) {
20
+ topLevelDefinitions.add(definition.name.value);
21
+ }
22
+ }
23
+ });
24
+ const document = toGraphQLOperation(cleanGraphQLDocument(loadedDocument, {
25
+ removeUnused: {
26
+ exclude: topLevelDefinitions
27
+ }
28
+ }));
29
+ return {
30
+ code: `export default JSON.parse(${JSON.stringify(JSON.stringify(document))})`,
31
+ meta: shouldWriteManifest ? {
32
+ quilt: {
33
+ graphql: document
34
+ }
35
+ } : undefined
36
+ };
37
+ },
38
+ async generateBundle() {
39
+ if (!shouldWriteManifest) return;
40
+ const operations = {};
41
+ for (const moduleId of this.getModuleIds()) {
42
+ const operation = this.getModuleInfo(moduleId)?.meta?.quilt?.graphql;
43
+ if (operation != null && typeof operation.id === 'string' && typeof operation.source === 'string') {
44
+ operations[operation.id] = operation.source;
45
+ }
46
+ }
47
+ await mkdir(dirname(manifestPath), {
48
+ recursive: true
49
+ });
50
+ await writeFile(manifestPath, JSON.stringify(operations, null, 2));
51
+ }
52
+ };
53
+ }
54
+ async function loadDocument(code, file, plugin, add, level = 0, seen = new Set()) {
55
+ const {
56
+ imports,
57
+ source
58
+ } = extractGraphQLImports(code);
59
+ const document = parse(source);
60
+ add?.(document, level);
61
+ if (imports.length === 0) {
62
+ return document;
63
+ }
64
+ const resolvedImports = await Promise.all(imports.map(async imported => {
65
+ if (seen.has(imported)) return;
66
+ seen.add(imported);
67
+ const resolvedId = await plugin.resolve(imported, file);
68
+ if (resolvedId == null) {
69
+ throw new Error(`Could not find ${JSON.stringify(imported)} from ${JSON.stringify(file)}`);
70
+ }
71
+ plugin.addWatchFile(resolvedId.id);
72
+ const contents = await readFile(resolvedId.id, {
73
+ encoding: 'utf8'
74
+ });
75
+ return loadDocument(contents, resolvedId.id, plugin, add, level + 1, seen);
76
+ }));
77
+ for (const importedDocument of resolvedImports) {
78
+ if (importedDocument == null) continue;
79
+ document.definitions.push(...importedDocument.definitions);
80
+ }
81
+ return document;
82
+ }
83
+
84
+ export { graphql };
@@ -1,3 +1,3 @@
1
1
  export { magicModuleEnv } from './env.esnext';
2
- export { magicModuleAppBrowserEntry, magicModuleAppComponent, magicModuleAppRequestRouter, quiltApp, quiltAppBrowser, quiltAppServer } from './app.esnext';
2
+ export { magicModuleAppBrowserEntry, magicModuleAppComponent, magicModuleAppRequestRouter, quiltAppBrowser, quiltAppServer } from './app.esnext';
3
3
  export { magicModuleRequestRouterEntry } from './request-router.esnext';
@@ -9,5 +9,25 @@ function smartReplace(values, options) {
9
9
  values
10
10
  });
11
11
  }
12
+ async function getNodePlugins() {
13
+ const [{
14
+ default: commonjs
15
+ }, {
16
+ default: json
17
+ }, {
18
+ default: nodeResolve
19
+ }, {
20
+ default: nodeExternals
21
+ }] = await Promise.all([import('@rollup/plugin-commonjs'), import('@rollup/plugin-json'), import('@rollup/plugin-node-resolve'), import('rollup-plugin-node-externals')]);
22
+ return [nodeExternals({}), nodeResolve({
23
+ preferBuiltins: true,
24
+ dedupe: []
25
+ // extensions,
26
+ // exportConditions,
27
+ }), commonjs(), json()];
28
+ }
29
+ function rollupPluginsToArray(plugins) {
30
+ return Array.isArray(plugins) ? [...plugins] : plugins ? [plugins] : [];
31
+ }
12
32
 
13
- export { smartReplace };
33
+ export { getNodePlugins, rollupPluginsToArray, smartReplace };