0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

URLの重複排除でパスとクエリを壊さない:小さなNode.jsサンプル

0
Posted at

Riddle Listというパズル紹介サイトを運営しています。この記事は、ブックマークのURLを比較するときに「同じ」とみなす範囲を明示する、小さな独立サンプルです。本番サイトへの機能追加ではありません。AIの補助を使って作成し、下記のテストを実行しました。

queryを消すとモードまで消える

https://example.com/play?mode=daily と https://example.com/play?mode=practice は、この例では別の保存先です。重複を減らすためにqueryを丸ごと削ると、利用者が選んだ開始位置を失います。一方、ホスト名の大小文字や標準ポートの差はURLパーサーで正規化できます。

ここではHTTPSの絶対URLだけを受け取り、認証情報を拒否し、fragmentだけを比較キーから除きます。パスの大小文字、末尾スラッシュ、queryの順序や同名パラメーターは保持します。fragmentが画面遷移を表すSPAには、そのまま適用できません。

実装と実行可能なテスト

以下を bookmark-identity.mjs に保存して node bookmark-identity.mjs を実行します。追加パッケージやネットワークアクセスは不要です。

// MIT; Leon Reed with AI assistance. Educational example, not production code.
import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';

export function bookmarkKey(value) {
  if (typeof value !== 'string' || !value.trim()) throw new TypeError('URL required');
  const url = new URL(value.trim());
  if (url.protocol !== 'https:') throw new TypeError('HTTPS required');
  if (url.username || url.password) throw new TypeError('Credentials not accepted');
  // A fragment is an in-page position in this specific bookmark contract.
  // Paths, query values, and query order deliberately remain significant.
  url.hash = '';
  return url.href;
}

export function uniqueBookmarks(values) {
  if (!Array.isArray(values)) throw new TypeError('Expected an array');
  const seen = new Set();
  return values.filter(value => {
    const key = bookmarkKey(value);
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

export function selfTest() {
  let checks = 0;
  const eq = (a, b) => { assert.deepEqual(a, b); checks++; };
  const different = (a, b) => { assert.notEqual(bookmarkKey(a), bookmarkKey(b)); checks++; };
  eq(bookmarkKey(' HTTPS://EXAMPLE.COM:443/play#rules '), 'https://example.com/play');
  eq(bookmarkKey('https://example.com'), 'https://example.com/');
  eq(bookmarkKey('https://example.com/play?mode=daily#rules'), 'https://example.com/play?mode=daily');
  for (const pair of [
    ['/play','/Play'], ['/play','/play/'],
    ['/play?mode=daily','/play?mode=practice'],
    ['/play?a=1&b=2','/play?b=2&a=1'],
    ['/play?a=1&a=2','/play?a=2&a=1'],
    ['/play?a=','/play'], ['/play?x=A','/play?x=a']
  ]) different(...pair.map(p => 'https://example.com' + p));
  for (const value of [null, 2, {}, '', ' ', '/play', 'javascript:alert(1)',
    'http://example.com/', 'data:text/plain,test', 'https://u:p@example.com/']) {
    assert.throws(() => bookmarkKey(value)); checks++;
  }
  const input = ['https://EXAMPLE.com:443/play#one','https://example.com/play#two',
    'https://example.com/play?mode=daily','https://example.com/play?mode=practice'];
  const before = [...input];
  eq(uniqueBookmarks(input), [input[0], input[2], input[3]]);
  eq(input, before);
  eq(uniqueBookmarks([]), []);
  assert.throws(() => uniqueBookmarks('bad')); checks++;
  eq(uniqueBookmarks(['https://example.com/?q=a','https://example.com/?q=b']).length, 2);
  return { checks, passed: true };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  console.log(JSON.stringify(selfTest()));
}

最初の値を残す理由

比較用キーと保存する元の値を分けています。同じキーが2回現れた場合、先にあった値だけを結果へ残します。入力配列は変更しません。不正な値は黙って捨てずに例外にします。部分的な救済が必要なインポーターなら、行ごとのエラー一覧を返す別の境界を設計します。

この処理はURLの正規化・重複判定だけです。リンク先へアクセスせず、公式サイト判定、危険なコンテンツの検査、リダイレクト先の検証はしません。署名付きURLやログインURLにも無条件で再利用しないでください。

運営しているRiddle Listでは、遊ぶ前の比較と公式の開始リンクを区別しています。Worldleの比較ページはその文脈へのリンクであり、テストデータではありません。テストはすべて合成のexample.com URLです。既存のJSON形式検証の記事とは別に、ここでは「URL同一性の契約」だけを扱いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?