CodeSampleX

샘플

tldts-core 7.4.10: Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup

검증된 샘플 — npm tldts-core 7.4.10: Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup. node 22 · linux…

sha256:e81c7fb5eff167f18c4e631f6068a33d2698002e199c7975cd23e3e693deed65

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-28

케이스

HOW
목표
Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup
패키지
심벌
  • fastPathLookup
  • getEmptyResult
  • parseImpl
  • resetResult
환경
node 22.23.2
생성일
2026-08-28T09:54:59Z

컨트랙트

  1. getEmptyResult returns a fresh result object with all fields initialized to null
  2. resetResult resets all result fields back to null for object reuse
  3. fastPathLookup directly identifies common ICANN suffixes com, org, edu, gov, net, de when allowPrivateDomains is false
  4. fastPathLookup returns false for unhandled suffixes or when allowPrivateDomains is enabled
  5. parseImpl extracts hostname, domain, subdomain, publicSuffix and domainWithoutSuffix from URLs
  6. parseImpl detects IPv4 and IPv6 hostnames and flags them with isIp when detectIp is enabled
  7. parseImpl flags IANA special-use domain names when detectSpecialUse option is true
  8. parseImpl ignores non-string inputs and preserves the result object without throwing

파일

  • 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: Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tldts-core@7.4.10
Demonstrate these symbols/APIs:
  - fastPathLookup
  - getEmptyResult
  - parseImpl
  - resetResult

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:463b86d766b36af4001b600efc78b7cfbb4c45d16d2e2552734efddc7fdbacd7","contract":["getEmptyResult returns a fresh result object with all fields initialized to null","resetResult resets all result fields back to null for object reuse","fastPathLookup directly identifies common ICANN suffixes com, org, edu, gov, net, de when allowPrivateDomains is false","fastPathLookup returns false for unhandled suffixes or when allowPrivateDomains is enabled","parseImpl extracts hostname, domain, subdomain, publicSuffix and domainWithoutSuffix from URLs","parseImpl detects IPv4 and IPv6 hostnames and flags them with isIp when detectIp is enabled","parseImpl flags IANA special-use domain names when detectSpecialUse option is true","parseImpl ignores non-string inputs and preserves the result object without throwing"],"goal":"Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup","kind":"HOW","packages":["pkg:npm/tldts-core@7.4.10"],"schemaVersion":1,"symbols":["fastPathLookup","getEmptyResult","parseImpl","resetResult"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tldts-core@7.4.10"],"schemaVersion":1,"subject":"pkg:npm/tldts-core@7.4.10","symbols":["fastPathLookup","getEmptyResult","parseImpl","resetResult"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tldts-core",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tldts-core",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tldts-core": "7.4.10"
      }
    },
    "node_modules/tldts-core": {
      "version": "7.4.10",
      "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.10.tgz",
      "integrity": "sha512-KnQjp53ZekKgm/r3l+u8kJGGzYgrWdP8+Mql7a4vijh2WE0IrZWspQj/TpTxDho/YxO+AnOZnIjQcCD+q6iJsw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-tldts-core",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for tldts-core@7.4.10",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "tldts-core": "7.4.10"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tldts-core@7.4.10"
  ],
  "symbols": [
    "fastPathLookup",
    "getEmptyResult",
    "parseImpl",
    "resetResult"
  ]
}
src/index.js
'use strict';

const {
  parseImpl,
  fastPathLookup,
  getEmptyResult,
  resetResult,
  setDefaults
} = require('tldts-core');

const FLAG = {
  HOSTNAME: 0,
  IS_VALID: 1,
  PUBLIC_SUFFIX: 2,
  DOMAIN: 3,
  SUB_DOMAIN: 4,
  ALL: 5
};

/**
 * Suffix lookup function using fastPathLookup and falling back to custom suffix rules.
 *
 * @param {string} hostname - Hostname being inspected.
 * @param {object} options - Suffix lookup options.
 * @param {object} out - Output suffix record to populate.
 */
function defaultSuffixLookup(hostname, options, out) {
  if (fastPathLookup(hostname, options, out)) {
    return;
  }
  // Custom suffix fallback for internal/custom domains
  if (hostname.endsWith('.custom')) {
    out.publicSuffix = 'custom';
    out.isIcann = false;
    out.isPrivate = true;
  }
}

/**
 * Parses a URL or hostname and extracts domain components into a result object.
 *
 * @param {string} url - Input URL or hostname string.
 * @param {object} [options] - Optional parsing options.
 * @param {function} [suffixLookup] - Suffix lookup handler.
 * @param {object} [targetResult] - Optional reusable result object.
 * @returns {object} Populated result object.
 */
function parseUrl(url, options, suffixLookup = defaultSuffixLookup, targetResult) {
  const result = targetResult || getEmptyResult();
  if (targetResult) {
    resetResult(result);
  }
  return parseImpl(url, FLAG.ALL, suffixLookup, options, result);
}

module.exports = {
  parseImpl,
  fastPathLookup,
  getEmptyResult,
  resetResult,
  setDefaults,
  FLAG,
  defaultSuffixLookup,
  parseUrl
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  parseImpl,
  fastPathLookup,
  getEmptyResult,
  resetResult,
  FLAG,
  defaultSuffixLookup,
  parseUrl
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof parseImpl, 'function', 'parseImpl must be a function');
  assert.equal(typeof fastPathLookup, 'function', 'fastPathLookup must be a function');
  assert.equal(typeof getEmptyResult, 'function', 'getEmptyResult must be a function');
  assert.equal(typeof resetResult, 'function', 'resetResult must be a function');
  assert.equal(typeof parseUrl, 'function', 'parseUrl helper must be a function');

  // 2. getEmptyResult produces fresh object with all null properties
  const fresh = getEmptyResult();
  assert.deepEqual(
    fresh,
    {
      hostname: null,
      isIp: null,
      subdomain: null,
      domain: null,
      publicSuffix: null,
      domainWithoutSuffix: null,
      isIcann: null,
      isPrivate: null,
      isSpecialUse: null
    },
    'getEmptyResult should return all-null result object'
  );

  // 3. resetResult resets mutated result back to all null
  fresh.hostname = 'test.example.com';
  fresh.domain = 'example.com';
  fresh.isIp = false;
  fresh.isIcann = true;
  resetResult(fresh);
  assert.equal(fresh.hostname, null, 'resetResult should clear hostname');
  assert.equal(fresh.domain, null, 'resetResult should clear domain');
  assert.equal(fresh.isIp, null, 'resetResult should clear isIp');
  assert.equal(fresh.isIcann, null, 'resetResult should clear isIcann');

  // 4. fastPathLookup detects common ICANN suffixes (com, org, edu, gov, net, de)
  const lookupOptions = { allowPrivateDomains: false };
  const suffixOut = { publicSuffix: null, isIcann: null, isPrivate: null };

  assert.equal(fastPathLookup('app.example.com', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'com');
  assert.equal(suffixOut.isIcann, true);
  assert.equal(suffixOut.isPrivate, false);

  assert.equal(fastPathLookup('community.example.org', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'org');

  assert.equal(fastPathLookup('portal.example.edu', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'edu');

  assert.equal(fastPathLookup('agency.example.gov', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'gov');

  assert.equal(fastPathLookup('network.example.net', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'net');

  assert.equal(fastPathLookup('site.example.de', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'de');

  // fastPathLookup returns false when allowPrivateDomains is true or suffix not in fast path
  assert.equal(fastPathLookup('app.example.com', { allowPrivateDomains: true }, suffixOut), false);
  assert.equal(fastPathLookup('site.example.custom', lookupOptions, suffixOut), false);

  // 5. parseImpl with fastPathLookup extracts hostname, subdomain, domain, publicSuffix
  const res = getEmptyResult();
  parseImpl('https://sub.blog.example.com:8080/path?query=1#hash', FLAG.ALL, defaultSuffixLookup, undefined, res);
  assert.equal(res.hostname, 'sub.blog.example.com');
  assert.equal(res.domain, 'example.com');
  assert.equal(res.subdomain, 'sub.blog');
  assert.equal(res.publicSuffix, 'com');
  assert.equal(res.domainWithoutSuffix, 'example');
  assert.equal(res.isIcann, true);
  assert.equal(res.isPrivate, false);
  assert.equal(res.isIp, false);

  // 6. parseImpl with custom fallback suffix lookup (.custom)
  resetResult(res);
  parseImpl('shop.service.custom', FLAG.ALL, defaultSuffixLookup, { extractHostname: false }, res);
  assert.equal(res.hostname, 'shop.service.custom');
  assert.equal(res.domain, 'service.custom');
  assert.equal(res.subdomain, 'shop');
  assert.equal(res.publicSuffix, 'custom');
  assert.equal(res.domainWithoutSuffix, 'service');
  assert.equal(res.isPrivate, true);

  // 7. parseImpl detects IPv4 and IPv6 addresses when detectIp is true
  resetResult(res);
  parseImpl('http://127.0.0.1:8080/api', FLAG.ALL, defaultSuffixLookup, { detectIp: true }, res);
  assert.equal(res.hostname, '127.0.0.1');
  assert.equal(res.isIp, true);
  assert.equal(res.domain, null);
  assert.equal(res.subdomain, null);

  resetResult(res);
  parseImpl('http://[::1]:3000/', FLAG.ALL, defaultSuffixLookup, { detectIp: true }, res);
  assert.equal(res.hostname, '::1');
  assert.equal(res.isIp, true);
  assert.equal(res.domain, null);

  // 8. parseImpl flags special-use domains when detectSpecialUse is true
  resetResult(res);
  parseImpl('http://localhost:3000', FLAG.ALL, defaultSuffixLookup, { detectSpecialUse: true }, res);
  assert.equal(res.hostname, 'localhost');
  assert.equal(res.isSpecialUse, true);

  // 9. parseImpl handles invalid types gracefully
  resetResult(res);
  parseImpl(null, FLAG.ALL, defaultSuffixLookup, undefined, res);
  assert.equal(res.hostname, null);

  // 10. parseUrl helper parses correctly and supports object reuse
  const reused = getEmptyResult();
  const out1 = parseUrl('https://api.example.org', undefined, defaultSuffixLookup, reused);
  assert.equal(out1, reused);
  assert.equal(reused.hostname, 'api.example.org');
  assert.equal(reused.domain, 'example.org');
  assert.equal(reused.subdomain, 'api');
  assert.equal(reused.publicSuffix, 'org');

  console.log('All tldts-core contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명