ecopages 0.2.1 → 0.3.1

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.
package/bin/cli.js CHANGED
@@ -1,18 +1,182 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { defineCommand, runMain } from 'citty';
4
- import { downloadTemplate } from 'giget';
5
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, readFileSync } from 'node:fs';
6
4
  import { spawn } from 'node:child_process';
7
- import { join } from 'node:path';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { parseArgs } from 'node:util';
8
9
  import { Logger } from '@ecopages/logger';
9
- import { createLaunchPlan, launchPlanRequiresExistingEntryFile } from './launch-plan.js';
10
+ import { createLaunchPlan, resolveEcoConfigFilePath } from './launch-plan.js';
11
+ import {
12
+ ECOPAGES_DEV_RESTART_EXIT_CODE,
13
+ ECOPAGES_DEV_RESTART_REASON_ENV,
14
+ isEcopagesEnvEnabled,
15
+ resolveDevelopmentRecoveryWatch,
16
+ } from '@ecopages/core/build';
17
+ import { fileSystem } from '@ecopages/file-system';
18
+ import { withBrandBanner } from './brand.js';
10
19
 
11
- const logger = new Logger('[ecopages:cli]', { debug: process.env.ECOPAGES_LOGGER_DEBUG === 'true' });
20
+ const logger = new Logger('[ecopages:cli]', { debug: isEcopagesEnvEnabled('ECOPAGES_LOGGER_DEBUG') });
12
21
 
13
22
  const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
14
23
 
15
- function runLaunchPlan(launchPlan) {
24
+ const sharedServerOptionDefinitions = {
25
+ port: {
26
+ type: 'string',
27
+ short: 'p',
28
+ },
29
+ hostname: {
30
+ type: 'string',
31
+ short: 'n',
32
+ },
33
+ 'base-url': {
34
+ type: 'string',
35
+ short: 'b',
36
+ },
37
+ debug: {
38
+ type: 'boolean',
39
+ short: 'd',
40
+ },
41
+ runtime: {
42
+ type: 'string',
43
+ },
44
+ 'entry-file': {
45
+ type: 'string',
46
+ short: 'e',
47
+ },
48
+ config: {
49
+ type: 'string',
50
+ short: 'c',
51
+ },
52
+ help: {
53
+ type: 'boolean',
54
+ short: 'h',
55
+ },
56
+ };
57
+
58
+ function getMainHelpText() {
59
+ return [
60
+ 'Usage: ecopages <command> [options]',
61
+ '',
62
+ 'Commands:',
63
+ ' init [dir] Initialize a new project from a template',
64
+ ' dev Start the development server',
65
+ ' dev:watch Start the development server with watch mode',
66
+ ' build Build the project for production',
67
+ ' start Start the production server',
68
+ ' preview Preview the production build',
69
+ ' types Write virtual-module types for tsc, then exit',
70
+ '',
71
+ 'Global options:',
72
+ ' -e, --entry-file <file> Entry file (default: app.ts)',
73
+ ' -c, --config <file> Ecopages config file (default: eco.config.ts)',
74
+ ' -h, --help Show help',
75
+ ' --version Show version',
76
+ ].join('\n');
77
+ }
78
+
79
+ const SHARED_SERVER_OPTION_HELP = {
80
+ port: ' -p, --port <port> Override ECOPAGES_PORT',
81
+ hostname: ' -n, --hostname <hostname> Override ECOPAGES_HOSTNAME',
82
+ 'base-url': ' -b, --base-url <baseUrl> Override ECOPAGES_BASE_URL',
83
+ debug: ' -d, --debug Enable debug logging',
84
+ runtime: ' --runtime <runtime> Force bun or node',
85
+ 'entry-file': ' -e, --entry-file <file> Entry file (default: app.ts)',
86
+ config: ' -c, --config <file> Ecopages config file (default: eco.config.ts)',
87
+ };
88
+
89
+ function getServerCommandHelpText(commandName, description, extraOptionLines = [], ignoredOptions = []) {
90
+ return [
91
+ `Usage: ecopages ${commandName} [options]`,
92
+ '',
93
+ description,
94
+ '',
95
+ 'Options:',
96
+ ...Object.entries(SHARED_SERVER_OPTION_HELP)
97
+ .filter(([option]) => !ignoredOptions.includes(option))
98
+ .map(([, line]) => line),
99
+ ...extraOptionLines,
100
+ ' -h, --help Show help',
101
+ ].join('\n');
102
+ }
103
+
104
+ function parseCommandArguments(rawArgs, options) {
105
+ return parseArgs({
106
+ args: rawArgs,
107
+ options,
108
+ allowPositionals: true,
109
+ strict: true,
110
+ });
111
+ }
112
+
113
+ function parseServerCommandArgs(rawArgs, definition) {
114
+ const commandName = definition.name;
115
+ const valueOptions = definition.valueOptions ?? {};
116
+ const booleanOptions = definition.booleanOptions ?? {};
117
+ const { values, positionals } = parseCommandArguments(rawArgs, {
118
+ ...sharedServerOptionDefinitions,
119
+ ...Object.fromEntries(Object.keys(valueOptions).map((option) => [option, { type: 'string' }])),
120
+ ...booleanOptions,
121
+ });
122
+
123
+ if (values.help) {
124
+ console.log(
125
+ getServerCommandHelpText(
126
+ commandName,
127
+ definition.description,
128
+ [...Object.values(valueOptions), ...(definition.optionHelpLines ?? [])],
129
+ definition.ignoredOptions,
130
+ ),
131
+ );
132
+ return { help: true };
133
+ }
134
+
135
+ if (positionals.length > 0) {
136
+ throw new Error(
137
+ `Positional entry file arguments are not supported for \`${commandName}\`. Use --entry-file <file> instead.`,
138
+ );
139
+ }
140
+
141
+ const entry = values['entry-file'] ?? 'app.ts';
142
+
143
+ return {
144
+ entry,
145
+ keepGoing: Boolean(values['keep-going']),
146
+ options: {
147
+ port: values.port,
148
+ hostname: values.hostname,
149
+ baseUrl: values['base-url'],
150
+ debug: values.debug,
151
+ runtime: values.runtime,
152
+ configFile: values.config,
153
+ distDir: values['dist-dir'],
154
+ },
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Signals the supervisor forwards to the child it runs.
160
+ *
161
+ * @remarks
162
+ * Without a handler, a signal ends the supervisor and leaves the child running as an orphan that keeps its
163
+ * port. Forwarding lets the child shut down first, and the supervisor exits from the child's `exit` event.
164
+ */
165
+ const FORWARDED_SIGNALS = ['SIGTERM', 'SIGINT'];
166
+
167
+ /**
168
+ * Exit code for a child that a signal terminated.
169
+ *
170
+ * @remarks
171
+ * Node reports such a child with a null exit code, which `process.exit(code || 0)` turned into success, so a
172
+ * build killed by the OOM killer (SIGKILL) looked like it had passed. Shells report the same case as 128 plus
173
+ * the signal number, and so does this.
174
+ */
175
+ function getSignalExitCode(signal) {
176
+ return 128 + (os.constants.signals[signal] ?? 0);
177
+ }
178
+
179
+ function runLaunchPlan(launchPlan, options = {}) {
16
180
  if (Object.keys(launchPlan.envOverrides).length > 0) {
17
181
  logger.debug(`Environment overrides: ${JSON.stringify(launchPlan.envOverrides)}`);
18
182
  }
@@ -25,12 +189,19 @@ function runLaunchPlan(launchPlan) {
25
189
  env: launchPlan.env,
26
190
  });
27
191
 
192
+ const forwardSignal = (signal) => {
193
+ child.kill(signal);
194
+ };
195
+ for (const signal of FORWARDED_SIGNALS) {
196
+ process.on(signal, forwardSignal);
197
+ }
198
+
28
199
  child.on('error', (error) => {
29
200
  if (error && error.code === 'ENOENT') {
30
201
  const hint =
31
202
  launchPlan.runtime === 'bun'
32
203
  ? 'Install Bun from https://bun.sh to continue.'
33
- : 'Reinstall ecopages and its dependencies so the packaged tsx runtime is available for Node.js launches.';
204
+ : 'Reinstall Node.js or run with --runtime bun if this app needs the Bun runtime.';
34
205
  logger.error(`Command not found: ${launchPlan.command}. ${hint}`);
35
206
  process.exit(1);
36
207
  }
@@ -39,222 +210,229 @@ function runLaunchPlan(launchPlan) {
39
210
  process.exit(1);
40
211
  });
41
212
 
42
- child.on('exit', (code) => {
43
- process.exit(code || 0);
213
+ child.on('exit', (code, signal) => {
214
+ for (const signal of FORWARDED_SIGNALS) {
215
+ process.off(signal, forwardSignal);
216
+ }
217
+
218
+ if (options.superviseDevRestarts && code === ECOPAGES_DEV_RESTART_EXIT_CODE) {
219
+ options.onDevRestart?.();
220
+ return;
221
+ }
222
+
223
+ if (code && options.onRestartFailure) {
224
+ logger.error(`The restarted development server exited with code ${code}.`);
225
+ options.onRestartFailure();
226
+ return;
227
+ }
228
+
229
+ process.exit(signal ? getSignalExitCode(signal) : code || 0);
230
+ });
231
+ }
232
+
233
+ /**
234
+ * Watches the project from before a restarted dev child launches until that child exits.
235
+ *
236
+ * @remarks
237
+ * A restarted child that exits with an error keeps the supervisor alive until the next change in the
238
+ * project or a linked workspace package, so an error in the config or a file it imports does not end
239
+ * the dev session. The watch starts before the child, so a fix saved while it was loading relaunches
240
+ * at once.
241
+ * @param {string} rootDir - Project root, the directory of the resolved config
242
+ */
243
+ async function watchProjectForRestart(rootDir) {
244
+ const { paths, ignored } = resolveDevelopmentRecoveryWatch(rootDir);
245
+ let changed = false;
246
+ let onNextChange;
247
+ const watcher = fileSystem.watch(paths, {
248
+ ignored,
249
+ onChange: () => {
250
+ changed = true;
251
+ onNextChange?.();
252
+ },
253
+ onError: (error) => {
254
+ logger.error('Cannot watch the project for the next restart', error);
255
+ process.exit(1);
256
+ },
44
257
  });
258
+ await watcher.ready;
259
+
260
+ return {
261
+ close: () => watcher.close(),
262
+ /** Calls `relaunch` once: now if the project changed since the watch started, otherwise on the next change. */
263
+ relaunchOnChange(relaunch) {
264
+ const run = () => {
265
+ onNextChange = undefined;
266
+ void watcher.close();
267
+ relaunch();
268
+ };
269
+ if (changed) {
270
+ logger.info('The project changed since the restart. Restarting...');
271
+ run();
272
+ return;
273
+ }
274
+ logger.info('Waiting for a change in the project to restart.');
275
+ onNextChange = run;
276
+ },
277
+ };
45
278
  }
46
279
 
47
280
  /**
48
- * Launch the entry file via the detected or forced runtime (bun or node).
49
- * Automatically detects eco.config.ts and applies preloads.
281
+ * Launch the entry file via the detected or forced runtime. Node and Bun get the same
282
+ * entry file and arguments.
50
283
  * @param {string[]} args - Arguments to pass to the entry file
51
- * @param {object} options - CLI options (watch, hot, port, hostname, etc.)
284
+ * @param {object} options - CLI options (watch, runtime, port, hostname, etc.)
52
285
  * @param {string} entryFile - Entry file to run
53
286
  */
54
- async function runEntryCommand(args, options = {}, entryFile = 'app.ts') {
55
- let launchPlan;
56
-
57
- try {
58
- launchPlan = await createLaunchPlan(args, options, entryFile);
59
- } catch (error) {
60
- const message = error instanceof Error ? error.message : String(error);
61
- logger.error(message);
62
- process.exit(1);
63
- }
287
+ async function runEntryCommand(args, options = {}, entryFile = 'app.ts', launchMode = 'start') {
288
+ const requiresBuiltBundle = launchMode === 'start';
289
+ const superviseDevRestarts = launchMode === 'dev';
64
290
 
65
- if (launchPlanRequiresExistingEntryFile(launchPlan) && !existsSync(entryFile)) {
291
+ if (!requiresBuiltBundle && !existsSync(entryFile)) {
66
292
  logger.error(`Error: Entry file "${entryFile}" not found in the current directory.`);
67
293
  process.exit(1);
68
294
  }
69
295
 
70
- runLaunchPlan(launchPlan);
71
- }
72
-
73
- /** Shared server argument definitions for citty commands. */
74
- const serverArgs = {
75
- entry: {
76
- type: 'positional',
77
- description: 'Entry file',
78
- default: 'app.ts',
79
- },
80
- port: {
81
- type: 'string',
82
- alias: ['p'],
83
- description: 'Override ECOPAGES_PORT',
84
- },
85
- hostname: {
86
- type: 'string',
87
- alias: ['n'],
88
- description: 'Override ECOPAGES_HOSTNAME',
89
- },
90
- 'base-url': {
91
- type: 'string',
92
- alias: ['b'],
93
- description: 'Override ECOPAGES_BASE_URL',
94
- },
95
- debug: {
96
- type: 'boolean',
97
- alias: ['d'],
98
- description: 'Enable debug logging (ECOPAGES_LOGGER_DEBUG=true)',
99
- },
100
- 'react-fast-refresh': {
101
- type: 'boolean',
102
- alias: ['r'],
103
- description: 'Enable React Fast Refresh for HMR',
104
- },
105
- runtime: {
106
- type: 'string',
107
- description: 'Force a specific runtime (bun or node)',
108
- },
109
- };
110
-
111
- const initCommand = defineCommand({
112
- meta: {
113
- name: 'init',
114
- description: 'Initialize a new project from a template',
115
- },
116
- args: {
117
- dir: {
118
- type: 'positional',
119
- description: 'Target directory name',
120
- required: true,
121
- },
122
- template: {
123
- type: 'string',
124
- description: 'Template name from ecopages/examples/',
125
- default: 'starter-jsx',
126
- },
127
- repo: {
128
- type: 'string',
129
- description: 'GitHub repo (user/repo)',
130
- default: 'ecopages/ecopages',
131
- },
132
- },
133
- async run({ args }) {
134
- const { dir, template, repo } = args;
296
+ const projectRoot = path.dirname(resolveEcoConfigFilePath(options) ?? path.resolve('eco.config.ts'));
297
+ const devRestartReason = 'configuration or environment change';
135
298
 
136
- if (existsSync(dir)) {
137
- logger.error(`Target directory already exists: ${dir}`);
299
+ const launchChild = async (restartReason) => {
300
+ const restartWatch = restartReason ? await watchProjectForRestart(projectRoot) : undefined;
301
+ const relaunchOnChange = () => restartWatch.relaunchOnChange(() => void launchChild(devRestartReason));
302
+ let launchPlan;
303
+ try {
304
+ launchPlan = await createLaunchPlan(args, options, entryFile, launchMode);
305
+ } catch (error) {
306
+ const message = error instanceof Error ? error.message : String(error);
307
+ logger.error(message);
308
+ if (restartWatch) {
309
+ relaunchOnChange();
310
+ return;
311
+ }
138
312
  process.exit(1);
139
313
  }
140
314
 
141
- logger.info(`Creating target directory '${dir}'...`);
315
+ if (restartReason) {
316
+ launchPlan.env[ECOPAGES_DEV_RESTART_REASON_ENV] = restartReason;
317
+ launchPlan.envOverrides[ECOPAGES_DEV_RESTART_REASON_ENV] = restartReason;
318
+ }
142
319
 
143
- try {
144
- await downloadTemplate(`github:${repo}/examples/${template}`, {
145
- dir,
146
- force: true,
147
- });
148
-
149
- const pkgPath = join(dir, 'package.json');
150
- if (existsSync(pkgPath)) {
151
- const projectPkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
152
- projectPkg.name = dir;
153
- writeFileSync(pkgPath, JSON.stringify(projectPkg, null, 2) + '\n');
154
- logger.info(`Renamed project to '${dir}'`);
155
- }
320
+ runLaunchPlan(launchPlan, {
321
+ superviseDevRestarts,
322
+ onDevRestart: () => {
323
+ void restartWatch?.close();
324
+ void launchChild(devRestartReason);
325
+ },
326
+ onRestartFailure: restartWatch ? relaunchOnChange : undefined,
327
+ });
328
+ };
156
329
 
157
- logger.info('Project initialized! Run `bun install && bun dev` to start.');
158
- } catch (err) {
159
- logger.error(`Failed to fetch template: ${err.message}`);
160
- process.exit(1);
161
- }
162
- },
163
- });
330
+ await launchChild();
331
+ }
164
332
 
165
- const devCommand = defineCommand({
166
- meta: {
167
- name: 'dev',
168
- description: 'Start the development server',
169
- },
170
- args: serverArgs,
171
- async run({ args }) {
172
- await runEntryCommand(['--dev'], { ...args, nodeEnv: 'development' }, args.entry);
173
- },
174
- });
333
+ async function runServerCommand(rawArgs, definition) {
334
+ const parsed = parseServerCommandArgs(rawArgs, definition);
175
335
 
176
- const devWatchCommand = defineCommand({
177
- meta: {
178
- name: 'dev:watch',
179
- description: 'Start the development server with watch mode (restarts on file changes)',
180
- },
181
- args: serverArgs,
182
- async run({ args }) {
183
- await runEntryCommand(['--dev'], { ...args, watch: true, nodeEnv: 'development' }, args.entry);
184
- },
185
- });
336
+ if (parsed.help) {
337
+ return;
338
+ }
339
+
340
+ const entry = definition.resolveEntry?.() ?? parsed.entry;
341
+ const entryArgs = [...definition.entryArgs];
342
+ if (parsed.keepGoing) entryArgs.push('--keep-going');
343
+ await runEntryCommand(
344
+ entryArgs,
345
+ { ...parsed.options, ...definition.optionOverrides, entryFile: entry },
346
+ entry,
347
+ definition.launchMode ?? definition.name,
348
+ );
349
+ }
186
350
 
187
- const devHotCommand = defineCommand({
188
- meta: {
189
- name: 'dev:hot',
190
- description: 'Start the development server with hot reload (HMR without restart)',
351
+ /**
352
+ * Commands that run an entry file, keyed by name. `launchMode` defaults to the name,
353
+ * and `resolveEntry` replaces the app entry (`app.ts`) with another script.
354
+ */
355
+ const SERVER_COMMANDS = {
356
+ dev: {
357
+ description: 'Start the development server.',
358
+ entryArgs: ['--dev'],
359
+ launchMode: 'dev',
360
+ optionOverrides: { nodeEnv: 'development' },
191
361
  },
192
- args: serverArgs,
193
- async run({ args }) {
194
- await runEntryCommand(['--dev'], { ...args, hot: true, nodeEnv: 'development' }, args.entry);
362
+ 'dev:watch': {
363
+ description: 'Start the development server with watch mode.',
364
+ entryArgs: ['--dev'],
365
+ launchMode: 'dev',
366
+ optionOverrides: { watch: true, nodeEnv: 'development' },
195
367
  },
196
- });
197
-
198
- const buildCommand = defineCommand({
199
- meta: {
200
- name: 'build',
201
- description: 'Build the project for production',
368
+ build: {
369
+ description:
370
+ 'Build the project for production: pre-render the Pages in src/pages, optimize assets and images, and write the result to dist.',
371
+ entryArgs: ['--build'],
372
+ booleanOptions: { 'keep-going': { type: 'boolean' } },
373
+ optionHelpLines: [' --keep-going Continue the build after a Page fails to render'],
374
+ optionOverrides: { nodeEnv: 'production' },
202
375
  },
203
- args: {
204
- entry: {
205
- type: 'positional',
206
- description: 'Entry file',
207
- default: 'app.ts',
208
- },
209
- runtime: {
210
- type: 'string',
211
- description: 'Force a specific runtime (bun or node)',
376
+ start: {
377
+ description: 'Start the production server.',
378
+ entryArgs: [],
379
+ optionOverrides: { nodeEnv: 'production' },
380
+ valueOptions: {
381
+ 'dist-dir':
382
+ ' --dist-dir <dir> Build output directory to start (default: the only one)',
212
383
  },
213
384
  },
214
- async run({ args }) {
215
- await runEntryCommand(['--build'], { nodeEnv: 'production', ...args }, args.entry);
385
+ types: {
386
+ description:
387
+ 'Load eco.config.ts so processors write the types for virtual modules such as ecopages:images, then exit. The app entry does not run. Run it before tsc.',
388
+ entryArgs: [],
389
+ resolveEntry: () => fileURLToPath(import.meta.resolve('@ecopages/core/config/write-types')),
390
+ ignoredOptions: ['port', 'hostname', 'base-url', 'entry-file'],
391
+ optionOverrides: { nodeEnv: 'production' },
216
392
  },
217
- });
218
-
219
- const startCommand = defineCommand({
220
- meta: {
221
- name: 'start',
222
- description: 'Start the production server',
223
- },
224
- args: serverArgs,
225
- async run({ args }) {
226
- await runEntryCommand([], { ...args, nodeEnv: 'production' }, args.entry);
393
+ preview: {
394
+ description: 'Build the project for production, then serve dist locally to preview it.',
395
+ entryArgs: ['--preview'],
396
+ optionOverrides: { nodeEnv: 'production' },
227
397
  },
228
- });
398
+ };
229
399
 
230
- const previewCommand = defineCommand({
231
- meta: {
232
- name: 'preview',
233
- description: 'Preview the production build',
234
- },
235
- args: serverArgs,
236
- async run({ args }) {
237
- await runEntryCommand(['--preview'], { ...args, nodeEnv: 'production' }, args.entry);
238
- },
239
- });
400
+ export async function runCli(rawArgs = process.argv.slice(2)) {
401
+ const [commandName, ...commandArgs] = rawArgs;
240
402
 
241
- export const mainCommand = defineCommand({
242
- meta: {
243
- name: 'ecopages',
244
- version: pkg.version,
245
- description: 'Ecopages CLI utilities',
246
- },
247
- subCommands: {
248
- init: initCommand,
249
- dev: devCommand,
250
- 'dev:watch': devWatchCommand,
251
- 'dev:hot': devHotCommand,
252
- build: buildCommand,
253
- start: startCommand,
254
- preview: previewCommand,
255
- },
256
- });
403
+ if (!commandName || commandName === '--help' || commandName === '-h') {
404
+ console.log(withBrandBanner(pkg.version, getMainHelpText()));
405
+ return;
406
+ }
407
+
408
+ if (commandName === '--version') {
409
+ console.log(pkg.version);
410
+ return;
411
+ }
412
+
413
+ try {
414
+ const serverCommand = Object.hasOwn(SERVER_COMMANDS, commandName) ? SERVER_COMMANDS[commandName] : undefined;
415
+ if (serverCommand) {
416
+ await runServerCommand(commandArgs, { name: commandName, ...serverCommand });
417
+ return;
418
+ }
419
+
420
+ switch (commandName) {
421
+ case 'init': {
422
+ const { runInitCommand } = await import('./init.js');
423
+ await runInitCommand(commandArgs, logger);
424
+ return;
425
+ }
426
+ default:
427
+ throw new Error(`Unknown command \`${commandName}\`.`);
428
+ }
429
+ } catch (error) {
430
+ const message = error instanceof Error ? error.message : String(error);
431
+ logger.error(message);
432
+ process.exit(1);
433
+ }
434
+ }
257
435
 
258
436
  if (!process.env.VITEST) {
259
- runMain(mainCommand);
437
+ runCli();
260
438
  }
@@ -0,0 +1,56 @@
1
+ import { repositoryName, withSubpath } from './git-template-source-shared.js';
2
+
3
+ export function normalizeGithubParts(parts, source) {
4
+ if (parts.length < 2) {
5
+ return null;
6
+ }
7
+
8
+ const [owner, repositoryPart, marker, ref, ...subpath] = parts;
9
+ const repository = `${owner}/${repositoryName(repositoryPart)}`;
10
+ if (marker === 'tree' || marker === 'blob') {
11
+ if (!ref) throw new Error(`Template URL '${source}' is missing a Git ref.`);
12
+ return `github:${withSubpath(repository, subpath)}#${ref}`;
13
+ }
14
+ return `github:${repository}`;
15
+ }
16
+
17
+ export function normalizeGitlabParts(parts) {
18
+ const markerIndex = parts.indexOf('-');
19
+ const treeIndex = parts.findIndex((part) => part === 'tree' || part === 'blob');
20
+ if (markerIndex > 0 && treeIndex > markerIndex && parts[treeIndex + 1]) {
21
+ const repository = parts.slice(0, markerIndex).map(repositoryName).join('/');
22
+ const ref = parts[treeIndex + 1];
23
+ const subpath = parts.slice(treeIndex + 2);
24
+ return `gitlab:${withSubpath(repository, subpath)}#${ref}`;
25
+ }
26
+ if (parts.length >= 2) return `gitlab:${parts.join('/')}`;
27
+ return null;
28
+ }
29
+
30
+ export function normalizeBitbucketParts(parts) {
31
+ if (parts.length < 2) {
32
+ return null;
33
+ }
34
+
35
+ const [workspace, repositoryPart, marker, ref, ...subpath] = parts;
36
+ const repository = `${workspace}/${repositoryName(repositoryPart)}`;
37
+ if (marker === 'src' && ref) {
38
+ return `bitbucket:${withSubpath(repository, subpath)}#${ref}`;
39
+ }
40
+ return `bitbucket:${repository}`;
41
+ }
42
+
43
+ export function normalizeSourcehutParts(parts) {
44
+ if (parts.length < 2) {
45
+ return null;
46
+ }
47
+
48
+ const treeIndex = parts.findIndex((part) => part === 'tree' || part === 'blob');
49
+ if (treeIndex > 1 && parts[treeIndex + 1]) {
50
+ const repository = parts.slice(0, treeIndex).map(repositoryName).join('/');
51
+ const ref = parts[treeIndex + 1];
52
+ const subpath = parts.slice(treeIndex + 2);
53
+ return `sourcehut:${withSubpath(repository, subpath)}#${ref}`;
54
+ }
55
+ return `sourcehut:${parts.join('/')}`;
56
+ }
@@ -0,0 +1,7 @@
1
+ export function repositoryName(value) {
2
+ return value.replace(/\.git$/u, '');
3
+ }
4
+
5
+ export function withSubpath(repository, subpath) {
6
+ return subpath.length > 0 ? `${repository}/${subpath.join('/')}` : repository;
7
+ }