uuid.ts 877 B

1234567891011121314151617
  1. /**
  2. * UUIDを生成するためのユーティリティ関数です。
  3. * crypto.randomUUID() のラッパーであり、非セキュアなコンテキスト(HTTPや古いブラウザなど)向けのフォールバック提供します。
  4. */
  5. export const generateUUID = (): string => {
  6. // crypto.randomUUID が利用可能かチェック (セキュアなコンテキスト HTTPS/localhost でのみ利用可能)
  7. if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
  8. return crypto.randomUUID();
  9. }
  10. // 非セキュアなコンテキストや古いブラウザ向けのフォールバック (RFC4122 v4 互換)
  11. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  12. const r = (Math.random() * 16) | 0;
  13. const v = c === 'x' ? r : (r & 0x3) | 0x8;
  14. return v.toString(16);
  15. });
  16. };