CodeSampleX

샘플

react-router 6.30.4: matchRoutes routing and param resolution

검증된 샘플 — npm react-router 6.30.4: matchRoutes routing and param resolution. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:134c2f72b31b38e8b2c59a2bf14917d01dc3f92a9441985a5cfbf2353d25c9e8

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

케이스

HOW
목표
matchRoutes routing and param resolution
패키지
심벌
  • generatePath
  • matchPath
  • matchRoutes
생성일
2026-08-27T21:15:25Z

컨트랙트

  1. matchRoutes matches nested route definitions against a URL pathname and extracts matched parameters
  2. matchRoutes returns null when no route branch matches the given pathname
  3. matchPath matches single route pattern against a URL pathname and parses params with end option
  4. matchPath returns null when URL pathname does not match route pattern
  5. generatePath generates URL path by interpolating params into route pattern
  6. generatePath throws an error when required param is missing

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: matchRoutes routing and param resolution
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/react-router@6.30.4
Demonstrate these symbols/APIs:
  - generatePath
  - matchPath
  - matchRoutes

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:16d557d827f11b3318a658322d9e5112de8b9cf603fb091e71bf3a196efd5bd1","contract":["matchRoutes matches nested route definitions against a URL pathname and extracts matched parameters","matchRoutes returns null when no route branch matches the given pathname","matchPath matches single route pattern against a URL pathname and parses params with end option","matchPath returns null when URL pathname does not match route pattern","generatePath generates URL path by interpolating params into route pattern","generatePath throws an error when required param is missing"],"goal":"matchRoutes routing and param resolution","kind":"HOW","packages":["pkg:npm/react-router@6.30.4"],"schemaVersion":1,"symbols":["generatePath","matchPath","matchRoutes"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react-router@6.30.4"],"schemaVersion":1,"subject":"pkg:npm/react-router@6.30.4","symbols":["generatePath","matchPath","matchRoutes"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-react-router-matching",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-react-router-matching",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "react-router": "6.30.4"
      }
    },
    "node_modules/@remix-run/router": {
      "version": "1.23.3",
      "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
      "integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    },
    "node_modules/react": {
      "version": "19.2.8",
      "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
      "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
      "license": "MIT",
      "peer": true,
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-router": {
      "version": "6.30.4",
      "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
      "integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
      "license": "MIT",
      "dependencies": {
        "@remix-run/router": "1.23.3"
      },
      "engines": {
        "node": ">=14.0.0"
      },
      "peerDependencies": {
        "react": ">=16.8"
      }
    }
  }
}
package.json
{
  "name": "sample-react-router-matching",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of react-router matchRoutes, matchPath, and generatePath routing utilities",
  "type": "module",
  "main": "src/index.js",
  "dependencies": {
    "react-router": "6.30.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "matchRoutes routing and param resolution",
  "kind": "HOW",
  "packages": [
    "pkg:npm/react-router@6.30.4"
  ],
  "symbols": [
    "generatePath",
    "matchPath",
    "matchRoutes"
  ]
}
src/index.js
import { matchRoutes, matchPath, generatePath } from 'react-router';

/**
 * Match a location against nested route configurations.
 *
 * @param {Array<object>} routes - Route hierarchy definition.
 * @param {string|object} location - Location pathname or object to match.
 * @param {string} [basename] - Base URL prefix.
 * @returns {Array<object>|null} Matched route branch with params or null.
 */
export function findMatchingRoutes(routes, location, basename = '/') {
  return matchRoutes(routes, location, basename);
}

/**
 * Match a single pathname against a route pattern.
 *
 * @param {string|object} pattern - Pattern string or pattern config object.
 * @param {string} pathname - Pathname to match.
 * @returns {object|null} Path match result containing params or null.
 */
export function checkPathMatch(pattern, pathname) {
  return matchPath(pattern, pathname);
}

/**
 * Generate a path by compiling a path pattern with params.
 *
 * @param {string} pattern - Route path pattern (e.g., '/users/:id').
 * @param {object} [params] - Params to interpolate into pattern.
 * @returns {string} Compiled path.
 */
export function buildPath(pattern, params = {}) {
  return generatePath(pattern, params);
}

export { matchRoutes, matchPath, generatePath };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  findMatchingRoutes,
  checkPathMatch,
  buildPath,
  matchRoutes,
  matchPath,
  generatePath,
} from '../src/index.js';

// Verify exported symbols
assert.equal(typeof matchRoutes, 'function', 'matchRoutes must be a function');
assert.equal(typeof matchPath, 'function', 'matchPath must be a function');
assert.equal(typeof generatePath, 'function', 'generatePath must be a function');
assert.equal(typeof findMatchingRoutes, 'function', 'findMatchingRoutes must be a function');
assert.equal(typeof checkPathMatch, 'function', 'checkPathMatch must be a function');
assert.equal(typeof buildPath, 'function', 'buildPath must be a function');

// 1. matchRoutes matches nested route definitions against a URL pathname and extracts matched parameters
const routeConfig = [
  {
    path: '/',
    id: 'root',
    children: [
      {
        index: true,
        id: 'home',
      },
      {
        path: 'orgs/:orgId',
        id: 'org',
        children: [
          {
            path: 'repos/:repoName',
            id: 'repo-detail',
          },
        ],
      },
    ],
  },
];

const matches = findMatchingRoutes(routeConfig, '/orgs/google/repos/csx');
assert(matches !== null, 'matchRoutes should find a match for valid nested route');
assert.equal(matches.length, 3, 'matchRoutes should return all 3 nested matching levels');
assert.equal(matches[0].route.id, 'root');
assert.equal(matches[1].route.id, 'org');
assert.equal(matches[2].route.id, 'repo-detail');
assert.equal(matches[2].params.orgId, 'google');
assert.equal(matches[2].params.repoName, 'csx');
assert.equal(matches[2].pathname, '/orgs/google/repos/csx');

// 2. matchRoutes returns null when no route branch matches the given pathname
const unmatched = findMatchingRoutes(routeConfig, '/unknown/path');
assert.equal(unmatched, null, 'matchRoutes should return null for unmatched route');

// 3. matchPath matches single route pattern against a URL pathname and parses params with end option
const matchEndTrue = checkPathMatch({ path: '/users/:userId', end: true }, '/users/42');
assert(matchEndTrue !== null, 'matchPath with end: true should match exact path');
assert.equal(matchEndTrue.params.userId, '42');
assert.equal(matchEndTrue.pathname, '/users/42');

const matchEndFalse = checkPathMatch({ path: '/users/:userId', end: false }, '/users/42/subpath');
assert(matchEndFalse !== null, 'matchPath with end: false should match path prefix');
assert.equal(matchEndFalse.params.userId, '42');
assert.equal(matchEndFalse.pathname, '/users/42');

// 4. matchPath returns null when URL pathname does not match route pattern
const matchFailed = checkPathMatch({ path: '/users/:userId', end: true }, '/users/42/subpath');
assert.equal(matchFailed, null, 'matchPath with end: true should return null on prefix-only match');

const matchCompletelyDifferent = checkPathMatch({ path: '/users/:userId', end: true }, '/projects/42');
assert.equal(matchCompletelyDifferent, null, 'matchPath should return null for non-matching pattern');

// 5. generatePath generates URL path by interpolating params into route pattern
const builtPath = buildPath('/users/:userId/posts/:postId', { userId: '100', postId: '200' });
assert.equal(builtPath, '/users/100/posts/200', 'generatePath should interpolate required params');

const optionalParamPath = buildPath('/users/:userId?', {});
assert.equal(optionalParamPath, '/users', 'generatePath should handle optional parameters');

const optionalParamProvided = buildPath('/users/:userId?', { userId: 'guest' });
assert.equal(optionalParamProvided, '/users/guest', 'generatePath should interpolate optional parameters when provided');

// 6. generatePath throws an error when required param is missing
assert.throws(
  () => {
    buildPath('/users/:userId', {});
  },
  (err) => {
    return err instanceof Error && err.message.includes('Missing ":userId" param');
  },
  'generatePath should throw when required param is missing'
);

console.log('Contract tests passed successfully.');

오리진 시더

익명