Could you please add an input box where I can enter a CID to check?
Assistant
Okay, I understand. You want to add an input box to the public-gateway-checker UI where users can enter a CID (Content Identifier) and trigger a check against the currently listed gateways. This will require changes in the HTML, TypeScript, and likely some adjustments to the existing GatewayNode class.
Here's a breakdown of the necessary modifications and the code changes to achieve this, based on the provided files:
1. Modify index.html:
Add an input field and a button to trigger the check. This should be placed in a logical location within the existing UI, likely above or below the existing results table.
html
<!-- Place this within the <div class="ph4-l pt4-l overflow-hidden"> element,
perhaps before the checker.stats div -->
<div class="pa2">
<input type="text" id="cid-input" class="input-reset ba b--black-20 pa2 mb2 db w-100" placeholder="Enter CID to check" />
<button id="check-cid-button" class="f6 button-reset bg-near-white ba b--black-20 pv2 ph3 tc black-70 hover-bg-black-10">Check CID</button>
</div>
2. Modify src/index.ts:
Add an event listener to the button to capture the user's input.
The Checker class also needs a method to receive the CID and trigger checks using it. This is why we'll add the method in the next step.
typescript
import { Workbox } from 'workbox-window'
import gateways from '../gateways.json'
import { Checker } from './Checker'
import { Log } from './Log'
import { loadMetrics } from './metrics'
const wb = new Workbox('/sw.js')
void wb.register()
// note: currently disabled and `.metricsConsentToggle` is currently display:none;
loadMetrics()
const log = new Log('App index')
window.checker = new Checker()
window.checker.checkGateways(gateways).catch((err) => {
log.error('Unexpected error')
log.error(err)
})
// Add event listener for the new button
const checkCidButton = document.getElementById('check-cid-button');
if (checkCidButton) {
checkCidButton.addEventListener('click', () => {
const cidInput = document.getElementById('cid-input') as HTMLInputElement;
if (cidInput?.value) {
window.checker.checkCid(cidInput.value);
}
});
}
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
3. Modify src/Checker.ts:
- Add a method to Checker to receive the CID input and check with all GatewayNodes.
```typescript
import { GatewayNode } from './GatewayNode'
import { Log } from './Log'
import { Results } from './Results'
import { Stats } from './Stats'
code
const log = new Log('Checker')
class Checker {
public readonly element: HTMLElement
public readonly nodes: GatewayNode[] = []
private readonly stats: Stats
private readonly results: Results
constructor () {
const element = document.getElementById('checker')
if (element == null) {
throw new Error('Element with Id "checker" not found.')
}
this.element = element
this.stats = new Stats(this)
this.results = new Results(this)
this.updateStats = this.updateStats.bind(this)
}
private updateStats (): void {
this.stats.update()
}
async checkGateways (gateways: string[]): Promise<void> {
const allChecks: Array<Promise<void>> = []
for (const gateway of gateways) {
const node = new GatewayNode(this.results, gateway, this.nodes.length)
this.nodes.push(node)
this.results.append(node.tag)
// void node.check()
setTimeout(() => {
allChecks.push(node.check().catch((err) => { log.error(err) }).finally(this.updateStats))
}, 100 * this.nodes.length)
}
// await Promise.all(allChecks).finally(this.updateStats)
}
async checkCid (cid: string): Promise<void> {
const allChecks: Array<Promise<void>> = [];
for (const node of this.nodes) {
allChecks.push(node.checkCid(cid).catch((err) => {log.error(err)}).finally(this.updateStats));
}
}
}
export { Checker }
```
4. Modify src/GatewayNode.ts:
- Add a method to GatewayNode to perform the check against the user supplied CID, based on the existing check method.
typescript
import { DEFAULT_IPFS_GATEWAY, HASH_STRING, HASH_TO_TEST, IMG_HASH, IPNS_PATH_TO_TEST, TRUSTLESS_RESPONSE_TYPES } from './constants'
import { Log } from './Log'
import { Results } from './Results'
import { Tag } from './Tag'
import { UiComponent } from './UiComponent'
const log = new Log('GatewayNode')
type CheckResult = 'pass' | 'fail' | 'skip'
interface CheckOutput {
status: CheckResult
time?: number
}
class GatewayNode extends UiComponent {
public readonly url: string
public readonly tag: Tag
private online: CheckResult = 'skip'
private cors: CheckResult = 'skip'
private ipns: CheckResult = 'skip'
private origin: CheckResult = 'skip'
private trustless: CheckResult = 'skip'
private time: number | undefined = undefined
constructor (parent: Results, url: string, index: number) {
super(parent, 'div', 'Node')
this.url = url
this.tag = new Tag('div', 'Node', {
'data-index': index.toString(),
})
}
private async checkOnline (): Promise<CheckOutput> {
try {
const start = performance.now()
const resp = await fetch(`${this.url}/ipfs/${HASH_TO_TEST}`, {
method: 'GET',
mode: 'no-cors',
})
if (resp.ok) {
const took = performance.now() - start
this.time = took
this.tag.element.querySelector('.Took')!.textContent = `${took.toFixed(0)}ms`
return { status: 'pass', time: took }
}
return { status: 'fail' }
} catch (e: any) {
log.error(`Error during online check ${this.url}`, e?.message)
return { status: 'fail' }
}
}
private async checkCors (): Promise<CheckOutput> {
try {
const resp = await fetch(`${this.url}/ipfs/${IMG_HASH}`)
if (resp.ok) {
return { status: 'pass' }
}
return { status: 'fail' }
} catch (e: any) {
log.error(`Error during CORS check ${this.url}`, e?.message)
return { status: 'fail' }
}
}
private async checkIpns (): Promise<CheckOutput> {
try {
const resp = await fetch(`${this.url}${IPNS_PATH_TO_TEST}`)
if (resp.ok) {
return { status: 'pass' }
}
return { status: 'fail' }
} catch (e: any) {
log.error(`Error during IPNS check ${this.url}`, e?.message)
return { status: 'fail' }
}
}
private async checkOrigin (): Promise<CheckOutput> {
try {
// if the url is `https://ipfs.io` or `https://dweb.link` then return "pass", as they are origin isolated.
if (this.url === 'https://ipfs.io' || this.url === 'https://dweb.link') {
return { status: 'pass' }
}
// If it's not, we'll perform a check by attempting a fetch to the /ipfs/<cid> using the subdomain, if possible
const url = new URL(this.url)
// Check if the url is already a subdomain gateway
if (url.hostname.includes('.')) {
const subdomain = url.hostname.split('.')[0]
// Check if the subdomain is a valid CID
// if it is not a valid CID, then it's not a subdomain gateway, and return fail
// It is a valid CID if it's a base32 string
if (!/^[a-z2-7]+$/.test(subdomain)) {
return {status: 'fail'}
}
const resp = await fetch(`https://${subdomain}.${url.hostname.substring(url.hostname.indexOf('.') + 1)}/ipfs/${IMG_HASH}`)
if (resp.ok) {
return { status: 'pass' }
}
}
return {status: 'fail'}
} catch (e: any) {
log.error(`Error during Origin check ${this.url}`, e?.message)
return { status: 'fail' }
}
}
private async checkTrustless (): Promise<CheckOutput> {
try {
for (const type of TRUSTLESS_RESPONSE_TYPES) {
const resp = await fetch(`${this.url}/ipfs/${HASH_TO_TEST}?format=${type}`, {
headers: {
'Accept': 'application/vnd.ipld.raw',
}
})
if (resp.ok) {
return { status: 'pass' }
}
}
return { status: 'fail' }
} catch (e: any) {
log.error(`Error during Trustless check ${this.url}`, e?.message)
return { status: 'fail' }
}
}
async check (): Promise<void> {
const onlineCheck = await this.checkOnline()
this.online = onlineCheck.status
this.tag.element.classList.add(this.online)
this.tag.element.querySelector('.Status')!.classList.add(this.online)
if (this.online === 'pass') {
const corsCheck = await this.checkCors()
this.cors = corsCheck.status
this.tag.element.querySelector('.Cors')!.classList.add(this.cors)
const ipnsCheck = await this.checkIpns()
this.ipns = ipnsCheck.status
this.tag.element.querySelector('.Ipns')!.classList.add(this.ipns)
const originCheck = await this.checkOrigin()
this.origin = originCheck.status
this.tag.element.querySelector('.Origin')!.classList.add(this.origin)
const trustlessCheck = await this.checkTrustless()
this.trustless = trustlessCheck.status
this.tag.element.querySelector('.Trustless')!.classList.add(this.trustless)
}
}
async checkCid (cid: string): Promise<void> {
try {
const start = performance.now()
const resp = await fetch(`${this.url}/ipfs/${cid}`, {
method: 'GET',
mode: 'no-cors',
})
const took = performance.now() - start
if (resp.ok) {
this.tag.element.querySelector('.Took')!.textContent = `${took.toFixed(0)}ms`
this.tag.element.classList.add('pass')
} else {
this.tag.element.classList.add('fail')
}
} catch (e: any) {
log.error(`Error during CID check ${this.url}`, e?.message)
this.tag.element.classList.add('fail')
}
}
}
export { GatewayNode }
Explanation of Changes:
HTML Changes: Added an input field (cid-input) and a button (check-cid-button).
index.ts Changes:
Added an event listener to the button. When the button is clicked, it gets the value from the input and calls the checkCid method on the checker instance.
Checker.ts Changes:
The new checkCid method iterates through the existing GatewayNode instances and calls the checkCid method on each, passing the CID from the input box.
GatewayNode.ts Changes:
The new checkCid method performs a fetch request to /ipfs/<cid> for the given gateway, setting the CSS classes according to the result.
How to Test:
Apply these changes to your local public-gateway-checker repository.
Build the project (e.g., npm run build).
Open index.html in your browser.
Enter a valid CID in the input box and click the "Check CID" button.
Observe the results, each row should display pass or fail depending if the CID was reachable on the gateway. The "Took" column will display the time it took to fetch the CID.
Important Notes:
Error Handling: The code includes basic error handling (e.g., catch blocks), but you might want to add more robust error reporting to the UI for a better user experience (e.g. displaying errors in a specific area).
UI/UX: Consider improving the UI by displaying a loading indicator or disabling the button while the checks are in progress.
Input Validation: You might want to add validation to the input field to ensure the user enters a valid CID format before initiating the checks.
Concurrency: The current implementation starts all checks at once, which might be resource intensive. Consider limiting concurrency or displaying a progress indicator to avoid overwhelming the user interface.
Existing Checks: This implementation leaves the existing checks untouched, and all checks can run concurrently, and you may want to only check online status for all nodes, or only perform the CID check depending on your preferences.
This should provide a good starting point for adding CID checking to your gateway checker. Let me know if you have further questions or would like to explore other improvements!