SHA256
47 lines
1.8 KiB
JavaScript
47 lines
1.8 KiB
JavaScript
// Public channel URLs use one-based publication positions, not blockchain block numbers.
|
|
// Order must match the channel feed: message time, then original block number.
|
|
function messageTimestamp(message) {
|
|
const value = Number(message?.timestampMs ?? message?.createdAtMs ?? 0);
|
|
return Number.isFinite(value) ? value : 0;
|
|
}
|
|
|
|
function blockNumber(message) {
|
|
const value = Number(message?.messageRef?.blockNumber);
|
|
return Number.isSafeInteger(value) ? value : 0;
|
|
}
|
|
|
|
export function sortedChannelPublications(messages = []) {
|
|
return [...messages].sort((a, b) => {
|
|
const byTime = messageTimestamp(a) - messageTimestamp(b);
|
|
return byTime !== 0 ? byTime : blockNumber(a) - blockNumber(b);
|
|
});
|
|
}
|
|
|
|
export function parsePublicationOrdinal(value) {
|
|
const text = String(value ?? '').trim();
|
|
if (!/^[1-9][0-9]*$/.test(text)) return null;
|
|
const number = Number(text);
|
|
return Number.isSafeInteger(number) ? number : null;
|
|
}
|
|
|
|
export function publicationAtOrdinal(messages, ordinal) {
|
|
const value = parsePublicationOrdinal(ordinal);
|
|
if (!value) return null;
|
|
return sortedChannelPublications(messages)[value - 1] || null;
|
|
}
|
|
|
|
export function ordinalForPublication(messages, reference) {
|
|
if (!reference) return null;
|
|
const number = Number(reference.blockNumber);
|
|
const hash = String(reference.blockHash || '').trim().toLowerCase();
|
|
const owner = String(reference.blockchainName || '').trim().toLowerCase();
|
|
const i = sortedChannelPublications(messages).findIndex((item) => {
|
|
const ref = item?.messageRef;
|
|
if (Number(ref?.blockNumber) !== number) return false;
|
|
if (hash && String(ref?.blockHash || '').trim().toLowerCase() !== hash) return false;
|
|
if (owner && String(item?.authorBlockchainName || '').trim().toLowerCase() !== owner) return false;
|
|
return true;
|
|
});
|
|
return i < 0 ? null : i + 1;
|
|
}
|