1/**
2 * Copyright © 2022 650 Industries.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7import assert from 'assert';
8import chalk from 'chalk';
9import fs from 'fs';
10import path from 'path';
11import prettyBytes from 'pretty-bytes';
12import { inspect } from 'util';
13
14import { Log } from '../log';
15import { DevServerManager } from '../start/server/DevServerManager';
16import { MetroBundlerDevServer } from '../start/server/metro/MetroBundlerDevServer';
17import { logMetroErrorAsync } from '../start/server/metro/metroErrorInterface';
18
19const debug = require('debug')('expo:export:generateStaticRoutes') as typeof console.log;
20
21type Options = { outputDir: string; minify: boolean };
22
23/** @private */
24export async function unstable_exportStaticAsync(projectRoot: string, options: Options) {
25  // NOTE(EvanBacon): Please don't use this feature.
26  Log.warn('Static exporting with Metro is an experimental feature.');
27
28  const devServerManager = new DevServerManager(projectRoot, {
29    minify: options.minify,
30    mode: 'production',
31    location: {},
32  });
33
34  await devServerManager.startAsync([
35    {
36      type: 'metro',
37    },
38  ]);
39
40  await exportFromServerAsync(projectRoot, devServerManager, options);
41
42  await devServerManager.stopAsync();
43}
44
45/** Match `(page)` -> `page` */
46function matchGroupName(name: string): string | undefined {
47  return name.match(/^\(([^/]+?)\)$/)?.[1];
48}
49
50export async function getFilesToExportFromServerAsync(
51  projectRoot: string,
52  {
53    manifest,
54    renderAsync,
55  }: {
56    manifest: any;
57    renderAsync: (pathname: string) => Promise<string>;
58  }
59): Promise<Map<string, string>> {
60  // name : contents
61  const files = new Map<string, string>();
62
63  await Promise.all(
64    getHtmlFiles({ manifest }).map(async (outputPath) => {
65      const pathname = outputPath.replace(/(index)?\.html$/, '');
66      try {
67        files.set(outputPath, '');
68        const data = await renderAsync(pathname);
69        files.set(outputPath, data);
70      } catch (e: any) {
71        await logMetroErrorAsync({ error: e, projectRoot });
72        throw new Error('Failed to statically export route: ' + pathname);
73      }
74    })
75  );
76
77  return files;
78}
79
80/** Perform all fs commits */
81export async function exportFromServerAsync(
82  projectRoot: string,
83  devServerManager: DevServerManager,
84  { outputDir }: Options
85): Promise<void> {
86  const devServer = devServerManager.getDefaultDevServer();
87  assert(devServer instanceof MetroBundlerDevServer);
88
89  const [manifest, resources, renderAsync] = await Promise.all([
90    devServer.getRoutesAsync(),
91    devServer.getStaticResourcesAsync({ mode: 'production' }),
92    devServer.getStaticRenderFunctionAsync({
93      mode: 'production',
94    }),
95  ]);
96
97  debug('Routes:\n', inspect(manifest, { colors: true, depth: null }));
98
99  const files = await getFilesToExportFromServerAsync(projectRoot, {
100    manifest,
101    async renderAsync(pathname: string) {
102      const template = await renderAsync(pathname);
103      return devServer.composeResourcesWithHtml({
104        mode: 'production',
105        resources,
106        template,
107      });
108    },
109  });
110
111  resources.forEach((resource) => {
112    files.set(resource.filename, resource.source);
113  });
114
115  fs.mkdirSync(path.join(outputDir), { recursive: true });
116
117  Log.log('');
118  Log.log(chalk.bold`Exporting ${files.size} files:`);
119  await Promise.all(
120    [...files.entries()]
121      .sort(([a], [b]) => a.localeCompare(b))
122      .map(async ([file, contents]) => {
123        const length = Buffer.byteLength(contents, 'utf8');
124        Log.log(file, chalk.gray`(${prettyBytes(length)})`);
125        const outputPath = path.join(outputDir, file);
126        await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
127        await fs.promises.writeFile(outputPath, contents);
128      })
129  );
130  Log.log('');
131}
132
133export function getHtmlFiles({ manifest }: { manifest: any }): string[] {
134  const htmlFiles = new Set<string>();
135
136  function traverseScreens(screens: string | { screens: any; path: string }, basePath = '') {
137    for (const value of Object.values(screens)) {
138      if (typeof value === 'string') {
139        let filePath = basePath + value;
140        if (value === '') {
141          filePath =
142            basePath === ''
143              ? 'index'
144              : basePath.endsWith('/')
145              ? basePath + 'index'
146              : basePath.slice(0, -1);
147        }
148        // TODO: Dedupe requests for alias routes.
149        addOptionalGroups(filePath);
150      } else if (typeof value === 'object' && value?.screens) {
151        const newPath = basePath + value.path + '/';
152        traverseScreens(value.screens, newPath);
153      }
154    }
155  }
156
157  function addOptionalGroups(path: string) {
158    const variations = getPathVariations(path);
159    for (const variation of variations) {
160      htmlFiles.add(variation);
161    }
162  }
163
164  traverseScreens(manifest.screens);
165
166  return Array.from(htmlFiles).map((value) => {
167    const parts = value.split('/');
168    // Replace `:foo` with `[foo]` and `*foo` with `[...foo]`
169    const partsWithGroups = parts.map((part) => {
170      if (part.startsWith(':')) {
171        return `[${part.slice(1)}]`;
172      } else if (part.startsWith('*')) {
173        return `[...${part.slice(1)}]`;
174      }
175      return part;
176    });
177    return partsWithGroups.join('/') + '.html';
178  });
179}
180
181// Given a route like `(foo)/bar/(baz)`, return all possible variations of the route.
182// e.g. `(foo)/bar/(baz)`, `(foo)/bar/baz`, `foo/bar/(baz)`, `foo/bar/baz`,
183export function getPathVariations(routePath: string): string[] {
184  const variations = new Set<string>([routePath]);
185  const segments = routePath.split('/');
186
187  function generateVariations(segments: string[], index: number): void {
188    if (index >= segments.length) {
189      return;
190    }
191
192    const newSegments = [...segments];
193    while (
194      index < newSegments.length &&
195      matchGroupName(newSegments[index]) &&
196      newSegments.length > 1
197    ) {
198      newSegments.splice(index, 1);
199      variations.add(newSegments.join('/'));
200      generateVariations(newSegments, index + 1);
201    }
202
203    generateVariations(segments, index + 1);
204  }
205
206  generateVariations(segments, 0);
207
208  return Array.from(variations);
209}
210