diff --git a/docs/reference/exit-codes.md b/docs/reference/exit-codes.md index 4ccc3cb1..cf7c98d6 100644 --- a/docs/reference/exit-codes.md +++ b/docs/reference/exit-codes.md @@ -5,14 +5,14 @@ StellarForge CLI uses predictable process exit codes so humans, scripts, and CI ## Stable Baseline | Exit code | Category | Meaning | -|---:|---------|---------| -| `0` x Success | The requested CLI operation completed successfully. | -| `1` x Unexpected failure | An unclassified exception reached the top-level CLI boundary. | -| `2` x Validation / usage failure | User input, command syntax, options, arguments, or other validated input was invalid. | -| `3` x Subprocess failure | A required external process or tool failed. | -| `4` x Internal failure | StellarForge detected a known internal failure condition that should not expose implementation details to the user. | -| `5` x Diagnostic failure | A diagnostic command completed normally but one or more required checks failed; used by `doctor` (environment health) and `stellarforge validate` (local project requirements). | -| `130` x Cancellation | The operation was interrupted by the user (SIGINT or equivalent) and stopped before completion. | +|---:|---|---| +| `0` | Success | The requested CLI operation completed successfully. | +| `1` | Unexpected failure | An unclassified exception reached the top-level CLI boundary. | +| `2` | Validation / usage failure | User input, command syntax, options, arguments, or other validated input was invalid. | +| `3` | Subprocess failure | A required external process or tool failed. | +| `4` | Internal failure | StellarForge detected a known internal failure condition that should not expose implementation details to the user. | +| `5` | Diagnostic failure | A diagnostic command completed normally but one or more required checks failed; used by `doctor` (environment health) and `stellarforge validate` (local project requirements). | +| `130` | Cancellation | The operation was interrupted by the user (SIGINT or equivalent) and stopped before completion. | These values are part of the CLI contract and should not be changed casually. New stable categories require deliberate review and documentation. @@ -33,12 +33,12 @@ An incomplete/partial diagnostic set (for example, checks without remediation) i ## Troubleshooting by Exit Code | Exit code | Start here | -|---:|---------| -| `2` if [Usage](troubleshooting.md#command-or-option-is-not-recognized), [`new`](troubleshooting.md#stellarforge-new-cannot-create-the-project), [project name](troubleshooting.md#project-name-is-rejected), [configuration](troubleshooting.md#configuration-file-is-rejected), [deployment network](troubleshooting.md#deployment-network-is-required), or [deployment identity](troubleshooting.md#deployment-identity-is-rejected) | -| `3` if [`dev`](troubleshooting.md#stellarforge-dev-says-no-supported-script-exists), [`test`](troubleshooting.md#stellarforge-test-cannot-find-a-workflow), or [Stellar CLI deployment](troubleshooting.md#stellar-cli-deployment-fails) | -| `5` if [`doctor`](troubleshooting.md#stellarforge-doctor-reports-failures), [`validate`](troubleshooting.md#stellarforge-validate-reports-required-project-failures) | -| `130` if [Cancellation](troubleshooting.md#cancelled-operation) | -| `1` or `<` if [Unexpected or internal failure](troubleshooting.md#unexpected-or-internal-failure) | +|---:|---| +| `2` | [Usage](troubleshooting.md#command-or-option-is-not-recognized), [`new`](troubleshooting.md#stellarforge-new-cannot-create-the-project), [project name](troubleshooting.md#project-name-is-rejected), [configuration](troubleshooting.md#configuration-file-is-rejected), [deployment network](troubleshooting.md#deployment-network-is-required), or [deployment identity](troubleshooting.md#deployment-identity-is-rejected) | +| `3` | [`dev`](troubleshooting.md#stellarforge-dev-says-no-supported-script-exists), [`test`](troubleshooting.md#stellarforge-test-cannot-find-a-workflow), or [Stellar CLI deployment](troubleshooting.md#stellar-cli-deployment-fails) | +| `5` | [`doctor`](troubleshooting.md#stellarforge-doctor-reports-failures), [`validate`](troubleshooting.md#stellarforge-validate-reports-required-project-failures) | +| `130` | [Cancellation](troubleshooting.md#cancelled-operation) | +| `1` or `4` | [Unexpected or internal failure](troubleshooting.md#unexpected-or-internal-failure) | The full index is at [Troubleshooting](troubleshooting.md#find-your-problem). diff --git a/eslint.config.js b/eslint.config.js index 2a8ea566..ccabff91 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -18,6 +18,31 @@ export default tseslint.config( rules: { '@typescript-eslint/consistent-type-imports': 'error', '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, + ], + }, + }, + { + files: ['templates/**/*.js'], + languageOptions: { + globals: { + AbortController: 'readonly', + AbortSignal: 'readonly', + Buffer: 'readonly', + Headers: 'readonly', + URL: 'readonly', + URLSearchParams: 'readonly', + clearInterval: 'readonly', + clearTimeout: 'readonly', + console: 'readonly', + fetch: 'readonly', + globalThis: 'readonly', + process: 'readonly', + setInterval: 'readonly', + setTimeout: 'readonly', + }, }, }, ); diff --git a/scripts/audit-workflow-permissions.mjs b/scripts/audit-workflow-permissions.mjs index 25593ac9..51849ebd 100644 --- a/scripts/audit-workflow-permissions.mjs +++ b/scripts/audit-workflow-permissions.mjs @@ -13,14 +13,6 @@ import fs from 'node:fs'; import path from 'node:path'; -/** Explicit per-job exceptions for workflows that must write. */ -const ARTIFACT_RETENTION_DAYS = { - test: 7, - coverage: 7, - security: 30, - release: 90, -}; - /** Artifact path patterns that must never be uploaded. */ const FORBIDDEN_ARTIFACT_PATTERNS = [ /\.env(\b|$)/i, diff --git a/src/commands/new.ts b/src/commands/new.ts index d802b995..000bf4d6 100644 --- a/src/commands/new.ts +++ b/src/commands/new.ts @@ -87,8 +87,7 @@ export function createNewCommand(options: NewCommandOptions = {}): Command { if (cancelled) { throw new ScaffoldingCancelledCliError(); - }, - ); + } if (signal.aborted) { throw signal.reason; diff --git a/src/deployment/project.ts b/src/deployment/project.ts index dd548a0e..02b3d9bf 100644 --- a/src/deployment/project.ts +++ b/src/deployment/project.ts @@ -59,7 +59,8 @@ export function runDeploymentPreflight( }); let identityOk = true; - let identityRemediation: string | undefined; + let identityRemediation = + 'Pass `--source ` with a valid named Stellar CLI identity alias.'; try { validateIdentityAlias(input.source); } catch (error) { diff --git a/src/generator/template-generation.ts b/src/generator/template-generation.ts index 3fbafbd2..1e2be9a0 100644 --- a/src/generator/template-generation.ts +++ b/src/generator/template-generation.ts @@ -16,7 +16,6 @@ import { ScaffoldingCancelledCliError, ValidationCliError, } from '../errors/errors.js'; -import { ValidationCliError } from '../errors/errors.js'; import { resolveCliVersion } from '../version.js'; import type { GenerationContext, @@ -120,6 +119,8 @@ function assertNotCancelled(isCancelled?: () => boolean): void { if (isCancelled?.()) { throw new ScaffoldingCancelledCliError(); } +} + /** * Measures the template tree before any file is written. Exceeding a documented * limit fails with a safe aggregate message that never embeds local paths or @@ -507,6 +508,7 @@ export function generateProjectFromTemplate( 'utf8', ); + assertNotCancelled(options.isCancelled); renameSync(stagingRoot, destination); } catch (error) { rmSync(stagingRoot, { recursive: true, force: true }); diff --git a/src/output/redaction.ts b/src/output/redaction.ts index 191e8ca5..b22297ec 100644 --- a/src/output/redaction.ts +++ b/src/output/redaction.ts @@ -18,7 +18,7 @@ const URL_WITH_QUERY = /\b([a-z][a-z0-9+.-]*:\/\/[^\s"'<>?]*\?)([^\s"'<>]*)/gi; * URL userinfo passwords, and token-bearing URL query parameters. */ function redactUrlQuery(query: string): string { - return query.replace(/([^?&#=]+)=([^&#]*)/g, (match, key, value) => { + return query.replace(/([^?&#=]+)=([^&#]*)/g, (match, key) => { if (!TOKEN_QUERY_KEY.test(String(key))) { return match; } diff --git a/templates/api-service/test/server.test.js b/templates/api-service/test/server.test.js index 80c072a6..d233bb35 100644 --- a/templates/api-service/test/server.test.js +++ b/templates/api-service/test/server.test.js @@ -562,7 +562,7 @@ test('malformed, oversized, and multi-value correlation ids are replaced', async await response.json(); } - const headers = new Headers(); + const headers = new globalThis.Headers(); headers.append('x-correlation-id', 'first'); headers.append('x-correlation-id', 'second'); const repeated = await globalThis.fetch( diff --git a/templates/basic-app/src/index.js b/templates/basic-app/src/index.js index 06759cb2..eb0729c1 100644 --- a/templates/basic-app/src/index.js +++ b/templates/basic-app/src/index.js @@ -70,6 +70,12 @@ try { ); writeLine(process.stdout, `horizonUrl: ${horizonUrl}`); writeLine(process.stdout, `rpcUrl: ${rpcUrl}`); + + globalThis.console.log( + `{{projectName}} is configured for the ${network.network} Stellar network.`, + ); + globalThis.console.log(`Horizon: ${network.horizonUrl}`); + globalThis.console.log(`RPC: ${network.rpcUrl}`); } catch (error) { const message = error instanceof Error ? error.message : 'Unknown startup failure.'; @@ -77,6 +83,3 @@ try { writeLine(process.stderr, `error: ${message}`); process.exit(1); } -globalThis.console.log(`{{projectName}} is configured for the ${network.network} Stellar network.`); -globalThis.console.log(`Horizon: ${network.horizonUrl}`); -globalThis.console.log(`RPC: ${network.rpcUrl}`); diff --git a/templates/basic-app/src/network.js b/templates/basic-app/src/network.js index b1b84422..700e1b68 100644 --- a/templates/basic-app/src/network.js +++ b/templates/basic-app/src/network.js @@ -6,7 +6,7 @@ export const SUPPORTED_NETWORKS = Object.freeze({ testnet: Object.freeze({ horizonUrl: DEFAULT_HORIZON_URL, rpcUrl: DEFAULT_RPC_URL, - networkPassphrase: DEFAULT_NETWORK_PASSPHRASE, + networkPassphrase: DEFAULT_NETWORK_PASSTHRASE, }), local: Object.freeze({ horizonUrl: 'http://127.0.0.1:8000', @@ -62,7 +62,7 @@ function validateEndpoint(label, value) { let parsed; try { - parsed = new URL(trimmed); + parsed = new globalThis.URL(trimmed); } catch { // Do not echo the input: URLs may contain credentials. throw new TypeError(`${label} is not a valid URL.`); diff --git a/templates/basic-app/test/lifecycle.test.js b/templates/basic-app/test/lifecycle.test.js index b050d744..3eae2317 100644 --- a/templates/basic-app/test/lifecycle.test.js +++ b/templates/basic-app/test/lifecycle.test.js @@ -1,4 +1,4 @@ -import assert from 'node:assert/strict'; +import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { fileURLToPath } from 'node:url'; @@ -103,13 +103,8 @@ test('reports actionable startup failure and exits non-zero for invalid configur stdio: ['ignore', 'pipe', 'pipe'], }); - let stdout = ''; let stderr = ''; - child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); - child.stdout.on('data', (chunk) => { - stdout += chunk; - }); child.stderr.on('data', (chunk) => { stderr += chunk; }); diff --git a/tests/deploy-preflight-validation.test.ts b/tests/deploy-preflight-validation.test.ts index 0575c11c..f6853bd2 100644 --- a/tests/deploy-preflight-validation.test.ts +++ b/tests/deploy-preflight-validation.test.ts @@ -104,12 +104,7 @@ describe('SW-161: deploy validation before subprocess side effects', () => { writeValidProject(root); writeConfig(root, config); expectZeroSubprocessSideEffects( - await runInvalidDeploy(root, [ - '--network', - 'testnet', - '--source', - 'deployer', - ]), + await runInvalidDeploy(root, ['--source', 'deployer']), ); }); }); @@ -247,7 +242,7 @@ describe('SW-161: deploy validation before subprocess side effects', () => { writeConfig(root, config); const captured = createCapturedTerminalOutput(); const child = new FakeChildProcess(); - const executor = vi.fn(() => child); + const executor = vi.fn((_spec: DevProcessSpec) => child); const command = createDeployCommand({ cwd: () => root, output: captured.output, diff --git a/tests/exit-code-reference.test.ts b/tests/exit-code-reference.test.ts index 437edccc..b4069a87 100644 --- a/tests/exit-code-reference.test.ts +++ b/tests/exit-code-reference.test.ts @@ -37,6 +37,7 @@ describe('exit-code reference conformance', () => { subprocess: 3, internal: 4, diagnostic: 5, + cancelled: 130, }); }); diff --git a/tests/package-metadata.test.ts b/tests/package-metadata.test.ts new file mode 100644 index 00000000..05e7ea45 --- /dev/null +++ b/tests/package-metadata.test.ts @@ -0,0 +1,142 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { basename, dirname, join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { repositoryRoot } from './helpers/index.js'; + +const CLI_PACKAGE_NAME = '@diginodes/stellarforge-cli'; + +// Documented support matrix (docs/guides/installation.md, +// docs/reference/platform-support.md). The CLI ships a bounded range; generated +// Node projects only pin the floor, which must stay inside that range. +const CLI_NODE_ENGINE = '>=22.13.0 <25'; +const TEMPLATE_NODE_ENGINE = '>=22.13.0'; + +// Templates that ship a package.json. smart-contract is Rust-only and has no +// manifest. The scripts block is the only intentional per-template variation; +// every other field is covered by the common policy asserted below. +const NODE_TEMPLATES: readonly { + id: string; + scripts: Record; +}[] = [ + { + id: 'basic-app', + scripts: { + start: 'node src/index.js', + check: 'node --check src/index.js && node --check src/network.js', + test: 'node --test', + }, + }, + { + id: 'api-service', + scripts: { + start: 'node src/start.js', + check: + 'node --check src/config.js && node --check src/stellar-client.js && node --check src/server.js && node --check src/start.js', + test: 'node --test test/*.test.js', + }, + }, + { + id: 'full-stack', + scripts: { + check: + 'node --check frontend/src/app.js && node --check backend/src/server.js && node --check backend/src/start.js', + test: 'node --test frontend/test/app.test.js backend/test/server.test.js', + 'start:backend': 'node backend/src/start.js', + }, + }, +]; + +function readManifest(path: string): Record { + return JSON.parse(readFileSync(path, 'utf8')) as Record; +} + +// Project-local files a script executes, e.g. the paths passed to `node --check` +// or `node --test`. A bare `node --test` (auto-discovery) yields nothing. +function referencedFiles(script: string): string[] { + return script.split(/\s+/).filter((token) => token.endsWith('.js')); +} + +// Resolves a script reference against the template tree. Plain paths must exist +// verbatim; glob references (e.g. `test/*.test.js`) must match at least one file. +function resolvesToFile(root: string, reference: string): boolean { + const directory = join(root, dirname(reference)); + + if (!existsSync(directory)) { + return false; + } + + const pattern = new RegExp( + `^${basename(reference) + .replace(/[.+^${}()|[\]\\]/g, '\\$&') + .replace(/\*/g, '.*')}$`, + ); + + return readdirSync(directory).some((name) => pattern.test(name)); +} + +describe('package metadata policy', () => { + describe('CLI manifest', () => { + const cli = readManifest(join(repositoryRoot, 'package.json')); + + it('publishes under the scoped package name', () => { + expect(cli.name).toBe(CLI_PACKAGE_NAME); + }); + + it('declares a concrete version, MIT license, and an explicit engine range', () => { + expect(cli.version).toMatch(/^\d+\.\d+\.\d+$/); + expect(cli.license).toBe('MIT'); + expect((cli.engines as { node?: string }).node).toBe(CLI_NODE_ENGINE); + }); + + it('is a public package', () => { + expect(cli.private).toBe(false); + }); + + it('keeps the declared engine range in sync with the documented matrix', () => { + const installation = readFileSync( + join(repositoryRoot, 'docs', 'guides', 'installation.md'), + 'utf8', + ); + + expect(installation).toContain(CLI_NODE_ENGINE); + }); + }); + + describe.each(NODE_TEMPLATES)('$id template', ({ id, scripts }) => { + const templateRoot = join(repositoryRoot, 'templates', id); + const manifest = readManifest(join(templateRoot, 'package.json')); + + it('stays parameterised by the project name instead of the CLI package', () => { + expect(manifest.name).toBe('{{projectName}}'); + expect(JSON.stringify(manifest)).not.toContain(CLI_PACKAGE_NAME); + }); + + it('declares a concrete version and the private flag, never the CLI publish flag', () => { + expect(manifest.version).toBe('0.1.0'); + expect(manifest.private).toBe(true); + }); + + // Explicit exception: generated projects ship no license field. + it('ships no license field', () => { + expect(manifest.license).toBeUndefined(); + }); + + it('pins the documented engine floor inside the CLI range', () => { + expect(manifest.engines).toEqual({ node: TEMPLATE_NODE_ENGINE }); + expect(CLI_NODE_ENGINE).toContain(TEMPLATE_NODE_ENGINE); + }); + + it('declares only scripts that resolve to bundled template files', () => { + expect(manifest.scripts).toEqual(scripts); + + for (const command of Object.values(scripts)) { + for (const file of referencedFiles(command)) { + expect( + resolvesToFile(templateRoot, file), + `${id}: missing ${file}`, + ).toBe(true); + } + } + }); + }); +});