Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add path rebasing to library adapter #227

Merged
merged 5 commits into from
Jul 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
- implement API server config and adapter
([#223](https://github.com/feltcoop/gro/pull/223))
- implement library adapter
([#226](https://github.com/feltcoop/gro/pull/226))
([#226](https://github.com/feltcoop/gro/pull/226),
[#227](https://github.com/feltcoop/gro/pull/227))

## 0.27.3

Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@
},
"files": [
"dist",
"src"
"src",
"changelog.md",
"contributing.md"
],
"engines": {
"node": ">=14.16.0"
Expand Down
71 changes: 48 additions & 23 deletions src/adapt/gro-adapter-node-library.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {print_spawn_result, spawn_process} from '@feltcoop/felt/util/process.js';
import {EMPTY_OBJECT} from '@feltcoop/felt/util/object.js';
import {strip_trailing_slash} from '@feltcoop/felt/util/path.js';
import {strip_start} from '@feltcoop/felt/util/string.js';

import type {Adapter} from './adapter.js';
import {Task_Error} from '../task/task.js';
Expand All @@ -20,7 +21,30 @@ import type {Build_Name} from '../build/build_config.js';
import {print_build_config_label, to_input_files} from '../build/build_config.js';
import {run_rollup} from '../build/rollup.js';
import type {Path_Stats} from '../fs/path_data.js';
import {load_package_json} from '../utils/package_json.js';
import type {Package_Json} from '../utils/package_json.js';

const name = '@feltcoop/gro-adapter-node-library';

// In normal circumstances, this adapter expects to handle
// only code scoped to `src/lib`, following SvelteKit conventions.
// It also supports Gro's current usecase that doesn't put anything under `lib/`,
// but that functionality may be removed to have one hardcoded happy path.
// In the normal case, the final package is flattened to the root directory,
// so `src/lib/index.ts` becomes `index.ts`.
// Import paths are *not* remapped by the adapter,
// but Gro's build process does map `$lib/` and `src/` to relative paths.
// This means all library modules must be under `src/lib` to work without additional transformation.
const LIBRARY_DIR = 'lib/';
// This function converts the build config's source file ids to the flattened base paths:
const source_id_to_library_base_path = (source_id: string, library_rebase_path: string): string => {
const base_path = source_id_to_base_path(source_id);
if (!base_path.startsWith(library_rebase_path)) {
throw Error(
`Source file does not start with library_rebase_path ${library_rebase_path}: ${base_path}`,
);
}
return strip_start(to_build_extension(base_path), library_rebase_path);
};

// TODO maybe add a `files` option to explicitly include source files,
// and fall back to inferring from the build config
Expand All @@ -29,24 +53,28 @@ import {load_package_json} from '../utils/package_json.js';
export interface Options {
build_name: Build_Name; // defaults to 'library'
dir: string; // defaults to `dist/${build_name}`
package_json: string; // defaults to 'package.json'
pack: boolean; // TODO temp hack for Gro's build -- treat the dist as a package to be published - defaults to true
library_rebase_path: string; // defaults to 'lib/', pass '' to avoid remapping -- TODO do we want to remove this after Gro follows SvelteKit conventions?
type: 'unbundled' | 'bundled'; // defaults to 'unbundled'
// TODO currently these options are only available for 'bundled'
esm: boolean; // defaults to true
cjs: boolean; // defaults to true
pack: boolean; // TODO temp hack for Gro's build -- treat the dist as a package to be published - defaults to true
}

export const create_adapter = ({
build_name = NODE_LIBRARY_BUILD_NAME,
dir = `${DIST_DIRNAME}/${build_name}`,
library_rebase_path = LIBRARY_DIR,
package_json = 'package.json',
pack = true,
type = 'unbundled',
esm = true,
cjs = true,
pack = true,
}: Partial<Options> = EMPTY_OBJECT): Adapter => {
dir = strip_trailing_slash(dir);
return {
name: '@feltcoop/gro-adapter-node-library',
name,
adapt: async ({config, fs, dev, log, args, timings}) => {
await fs.remove(dir);

Expand All @@ -59,8 +87,8 @@ export const create_adapter = ({

const files = to_input_files(build_config.input);

const timing_to_bundle_with_rollup = timings.start('bundle with rollup');
if (type === 'bundled') {
const timing_to_bundle_with_rollup = timings.start('bundle with rollup');
if (type !== 'bundled') throw Error();
// TODO use `filters` to select the others..right?
if (!files.length) {
Expand Down Expand Up @@ -99,15 +127,20 @@ export const create_adapter = ({
map_watch_options,
});
}
timing_to_bundle_with_rollup();
}
timing_to_bundle_with_rollup();

const timing_to_copy_dist = timings.start('copy build to dist');
const filter = type === 'bundled' ? bundled_dist_filter : undefined;
await copy_dist(fs, build_config, dev, dir, log, filter, pack);
await copy_dist(fs, build_config, dev, dir, log, filter, pack, library_rebase_path);
timing_to_copy_dist();

const pkg = await load_package_json(fs);
let pkg: Package_Json;
try {
pkg = JSON.parse(await fs.read_file(package_json, 'utf8'));
} catch (err) {
throw Error(`Adapter ${name} failed to load package_json at path ${package_json}: ${err}`);
}

// If the output is treated as a package, it needs some special handling to get it ready.
if (pack) {
Expand Down Expand Up @@ -147,7 +180,7 @@ export const create_adapter = ({
'./package.json': './package.json',
};
for (const source_id of files) {
const path = `./${to_build_extension(source_id_to_base_path(source_id))}`;
const path = `./${source_id_to_library_base_path(source_id, library_rebase_path)}`;
pkg_exports[path] = path;
}
pkg.exports = pkg_exports;
Expand Down Expand Up @@ -185,21 +218,13 @@ const bundled_dist_filter = (id: string, stats: Path_Stats): boolean =>
const to_possible_filenames = (paths: string[]): string[] =>
paths.flatMap((path) => {
const lower = path.toLowerCase();
return [lower, `${lower}.md`];
const upper = path.toUpperCase();
return [lower, `${lower}.md`, upper, `${upper}.md`];
});

// these are the files npm includes by default; unlike npm, the only extension we support is `.md`
// these are a subset of the files npm includes by default --
// unlike npm, the only extension we support is `.md`
const PACKAGE_FILES = new Set(
['package.json'].concat(
to_possible_filenames([
'README',
'CHANGES',
'CHANGELOG',
'HISTORY',
'LICENSE',
'LICENCE',
'NOTICE',
]),
),
['package.json'].concat(to_possible_filenames(['README', 'LICENSE'])),
);
const OTHER_PACKAGE_FILES = new Set(to_possible_filenames(['GOVERNANCE']));
const OTHER_PACKAGE_FILES = new Set(to_possible_filenames(['CHANGELOG', 'GOVERNANCE']));
9 changes: 5 additions & 4 deletions src/adapt/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {relative, dirname} from 'path';
import type {Logger} from '@feltcoop/felt/util/log.js';
import {strip_end} from '@feltcoop/felt/util/string.js';
import {strip_end, strip_start} from '@feltcoop/felt/util/string.js';

import type {Build_Config} from '../build/build_config.js';
import type {Filesystem} from '../fs/filesystem.js';
Expand All @@ -24,9 +24,10 @@ export const copy_dist = async (
log: Logger,
filter?: (id: string, stats: Path_Stats) => boolean,
pack: boolean = true, // TODO reconsider this API, see `gro-adapter-node-library`
rebase_path: string = '',
): Promise<void> => {
const build_out_dir = to_build_out_path(dev, build_config.name);
const externals_dir = to_build_out_path(dev, build_config.name, EXTERNALS_BUILD_DIRNAME);
const build_out_dir = to_build_out_path(dev, build_config.name, rebase_path);
const externals_dir = build_out_dir + EXTERNALS_BUILD_DIRNAME;
log.info(`copying ${print_path(build_out_dir)} to ${print_path(dist_out_dir)}`);
const typemap_files: string[] = [];
await fs.copy(build_out_dir, dist_out_dir, {
Expand All @@ -53,7 +54,7 @@ export const copy_dist = async (
const dist_source_id = pack
? `${dist_out_dir}/${SOURCE_DIRNAME}/${source_base_path}`
: `${paths.source}${source_base_path}`;
const dist_out_path = `${dist_out_dir}/${base_path}`;
const dist_out_path = `${dist_out_dir}/${strip_start(base_path, rebase_path)}`;
const typemap_source_path = relative(dirname(dist_out_path), dist_source_id);
const typemap = JSON.parse(await fs.read_file(id, 'utf8'));
typemap.sources[0] = typemap_source_path; // haven't seen any exceptions that would break this
Expand Down
1 change: 1 addition & 0 deletions src/gro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const config: Gro_Config_Creator = async ({dev}) => {
// TODO temp hack - unlike most libraries, Gro ships its dist/ as a sibling to src/,
// and this flag opts out of the default library behavior
pack: false,
library_rebase_path: '',
}),
]),
};
Expand Down