ecopages 0.2.1 → 0.3.0

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