Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add helia-script-tag example #13

Merged
merged 16 commits into from
Mar 31, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ jobs:
- helia-101
- helia-cjs
- helia-webpack
- helia-script-tag
defaults:
run:
working-directory: examples/${{ matrix.project }}
Expand Down Expand Up @@ -69,6 +70,7 @@ jobs:
- helia-101
- helia-cjs
- helia-webpack
- helia-script-tag
steps:
- uses: convictional/trigger-workflow-and-wait@f69fa9eedd3c62a599220f4d5745230e237904be
with:
Expand Down
17 changes: 17 additions & 0 deletions examples/helia-script-tag/.github/pull_request_template.md
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw this in other examples too, should this file be in the root like .github/workflows/ci.yml

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, this gets copied to the per-example repo and is used when a user tries to open a PR there - for example: https://github.com/ipfs-examples/helia-101/blob/main/.github/pull_request_template.md

If we placed this in the root of this repo, it would show a "Please don't open a PR here" message when someone tried to open a PR here, which is not what we want.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there some documentation we should add so that is clearer for contributors? What would have helped you @whizzzkid ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can have an example generator which updates and maintains boilerplate stuff.

This looks quite hectic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the generator is simply forking an example and then continuing. I don't want to maintain a generator, and I don't want to break the ipfs-examples or fork&go pattern without good reason and less work

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# ⚠️ IMPORTANT ⚠️

# Please do not create a Pull Request for this repository

The contents of this repository are automatically synced from the parent [Helia Examples Project](https://github.com/ipfs-examples/helia-examples) so any changes made to the standalone repository will be lost after the next sync.

Please open a PR against [Helia Examples](https://github.com/ipfs-examples/helia-examples) instead.

## Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.

1. Fork the [Helia Examples Project](https://github.com/ipfs-examples/helia-examples)
2. Create your Feature Branch (`git checkout -b feature/amazing-example`)
3. Commit your Changes (`git commit -a -m 'feat: add some amazing example'`)
4. Push to the Branch (`git push origin feature/amazing-example`)
5. Open a Pull Request
19 changes: 19 additions & 0 deletions examples/helia-script-tag/.github/workflows/sync.yml
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see this in other examples too, is this only to sync feature branches?

Questions (Most likely for @achingbrain):

  • can't this be in the root alongside workflow.yml
  • github has a setting to force branch update and merge queue which also achieves something similar, how's this different? seems boilerplate overhead.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is copied to the per-example repo and is then triggered by CI on this repo, it pulls a subfolder from this repo to the per-example repo and replaces all the files there.

I would rather the changes were pushed from a build on this repo instead of triggering a pull from every per-example repo but GitHub's permissions model prevented it, at the time at least.

If there's a better way of doing this PRs are gratefully accepted!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could do similar to what exists in our {org}/.github-mgmt repos, or unified CI, where files that are to be copied to other repos are in a central location, and we copy/override example subfolders & commit before pushing to example repos.

This is probably already supported by https://github.com/ipfs-examples/github-mgmt with the repositories.*.files.content key for each repo

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: pull

on:
workflow_dispatch

jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Pull from another repository
uses: ipfs-examples/actions-pull-directory-from-repo@main
with:
source-repo: ipfs-examples/helia-examples
source-folder-path: examples/${{ github.event.repository.name }}
source-branch: main
target-branch: main
git-username: github-actions
git-email: github-actions@github.com
8 changes: 8 additions & 0 deletions examples/helia-script-tag/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules
build
dist
.docs
.coverage
node_modules
package-lock.json
yarn.lock
130 changes: 130 additions & 0 deletions examples/helia-script-tag/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<p align="center">
<a href="https://github.com/ipfs/helia" title="Helia">
<img src="https://raw.githubusercontent.com/ipfs/helia/main/assets/helia.png" alt="Helia logo" width="300" />
</a>
</p>

<h3 align="center"><b>Using Helia via <code><script/></code> tags from CDN</b></h3>

<p align="center">
<img src="https://raw.githubusercontent.com/jlord/forkngo/gh-pages/badges/cobalt.png" width="200">
<br>
<a href="https://ipfs.github.io/helia/modules/helia.html">Explore the docs</a>
.
<a href="https://codesandbox.io/p/sandbox/helia-script-tag-g420c3">View codesandbox Demo</a>
·
<a href="https://github.com/ipfs-examples/helia-examples/issues">Report Bug</a>
·
<a href="https://github.com/ipfs-examples/helia-examples/issues">Request Feature/Example</a>
</p>

## Table of Contents

- [Table of Contents](#table-of-contents)
- [About The Project](#about-the-project)
- [Getting Started](#getting-started)
- [Prerequisites](#prerequisites)
- [Installation and Running example](#installation-and-running-example)
- [Usage](#usage)
- [Documentation](#documentation)
- [Contributing](#contributing)
- [Want to hack on IPFS?](#want-to-hack-on-ipfs)

## About The Project

- Read the [docs](https://ipfs.github.io/helia/modules/helia.html)
- Look into other [examples](https://github.com/ipfs-examples/helia-examples) to learn how to spawn a Helia node in Node.js and in the Browser
- Visit https://dweb-primer.ipfs.io to learn about IPFS and the concepts that underpin it
- Head over to https://proto.school to take interactive tutorials that cover core IPFS APIs
- Check out https://docs.ipfs.io for tips, how-tos and more
- See https://blog.ipfs.io for news and more
- Need help? Please ask 'How do I?' questions on https://discuss.ipfs.io

## Getting Started

### Prerequisites

Make sure you have installed all of the following prerequisites on your development machine:

- Git - [Download & Install Git](https://git-scm.com/downloads). OSX and Linux machines typically have this already installed.
- Node.js - [Download & Install Node.js](https://nodejs.org/en/download/) and the npm package manager.

### Installation and Running example

```console
> npm install
> npm start
```

Then open your browser to http://localhost:8888.

## Usage

This example is basic demo and proof of concept for using helia via script tags. Other examples use build-scripts that may be too complicated for your needs. If you have a website where you manage your dependencies via script tags in an HTML file, you may benefit from looking at this example instead of the others at https://github.com/ipfs-examples/helia-examples/tree/main/examples.

If you are seeing errors like `ERR_REQUIRE_ESM` or `ERR_PACKAGE_PATH_NOT_EXPORTED` when trying to use this example, please check out `/examples/helia-cjs` instead.

The main areas of focus should be two files: `index.html` and `src/index.js`.

If you're confused about what the different methods under 'Some Suggestions' are doing, you may want to check out [helia-101](https://github.com/ipfs-examples/helia-101) for a full breakdown of the code.

### Using the example

The page you will see is broken up into 4 sections:

1. The intro: title and global variables you can play with in your browser console
2. Node Status: The status of the helia node, which is updated every 500ms
* Helia will start up on page load. You can use the 'Start Helia' and 'Stop Helia' to call `helia.start()` and `helia.stop()` respectively.
* Updated content (look for `nodeUpdateInterval = ` in `src/index.js` to change or edit what's updated):
* Node Status - shows either "Online" or "Offline".
* ID - Shows the PeerId of your Helia node.
* Discovered Peers - The count of peers discovered. Check the event log at the bottom of the page to see their IDs.
* Connected Peers - The count of peers your helia node is connected to. Also, a list of their `PeerId`s will render if the count is > 0.
3. Suggestions: Try out these code snippets in your browser terminal, in order.
4. Event Log: Elapsed-TimeStamped messages showing you some of what Helia and it's managed libp2p node are doing. This event log shows:
* instantiation of the libp2p instance passed to helia
* instantiation of the Helia node
* peer discovery
* peer connection
* peer disconnection

_For more examples, please refer to the [Documentation](#documentation)_

## Documentation

- [IPFS Primer](https://dweb-primer.ipfs.io/)
- [IPFS Docs](https://docs.ipfs.io/)
- [Tutorials](https://proto.school)
- [More examples](https://github.com/ipfs-examples/helia-examples)
- [API - Helia](https://ipfs.github.io/helia/modules/helia.html)
- [API - @helia/unixfs](https://ipfs.github.io/helia-unixfs/modules/helia.html)

## Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.

1. Fork the IPFS Project
2. Create your Feature Branch (`git checkout -b feature/amazing-feature`)
3. Commit your Changes (`git commit -a -m 'feat: add some amazing feature'`)
4. Push to the Branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## Want to hack on IPFS?

[![](https://cdn.rawgit.com/jbenet/contribute-ipfs-gif/master/img/contribute.gif)](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md)

The IPFS implementation in JavaScript needs your help! There are a few things you can do right now to help out:

Read the [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md) and [JavaScript Contributing Guidelines](https://github.com/ipfs/community/blob/master/CONTRIBUTING_JS.md).

- **Check out existing issues** The [issue list](https://github.com/ipfs/helia/issues) has many that are marked as ['help wanted'](https://github.com/ipfs/helia/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22help+wanted%22) or ['difficulty:easy'](https://github.com/ipfs/helia/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Adifficulty%3Aeasy) which make great starting points for development, many of which can be tackled with no prior IPFS knowledge
- **Look at the [Helia Roadmap](https://github.com/ipfs/helia/blob/main/ROADMAP.md)** This are the high priority items being worked on right now
- **Perform code reviews** More eyes will help
a. speed the project along
b. ensure quality, and
c. reduce possible future bugs
- **Add tests**. There can never be enough tests

[cid]: https://docs.ipfs.tech/concepts/content-addressing "Content Identifier"
[Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
[libp2p]: https://libp2p.io
Binary file added examples/helia-script-tag/favicon.ico
Binary file not shown.
119 changes: 119 additions & 0 deletions examples/helia-script-tag/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>IPFS in the Browser via Helia</title>
<link rel="icon favicon" href="favicon.ico" />
<link href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism.css" rel="stylesheet" />
</head>
<body>
<h1>IPFS in the Browser via Helia</h1>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we want to mention <script> tag here?

<p>
This page creates an IPFS Helia node in your browser and sets a few other useful components into the
global Javascript namespace:
<ul>
<li><b><em style="background-color:#d7d6d6">helia</em></b> - A helia instance. You can access the <a href="https://www.npmjs.com/package/libp2p" target="_blank">libp2p</a> instance used by helia with <b><em style="background-color:#d7d6d6">helia.libp2p</em></b></li>
<li><b><em style="background-color:#d7d6d6">heliaFs</em></b> - A <a href="https://www.npmjs.com/package/@helia/unixfs" target="_blank">@helia/unixFS</a> instance</li>
<li><b><em style="background-color:#d7d6d6">discoveredPeers</em></b> - A <b><em style="background-color:#d7d6d6">Map&lt;peerIdString, peerDiscoveryEventDetail&gt;</em></b> that is filled as we discover peers</li>
</ul>
Open the console to play around with them.
</p>
<p>
Note that opening two tabs of this page in the same browser won't work
well, because they will share node configuration. You'll end up trying to
run two instances of the same node, with the same private key and
identity, which is a Bad Idea.
</p>
<hr />
<div>
<button class="e2e-startHelia" onclick="window.helia.start()">Start Helia</button>
<button class="e2e-stopHelia" onclick="window.helia.stop()">Stop Helia</button>
</div>
<h1 id="status">Node status: <span id="statusValue">Not Started</span></h1>
<div id="nodeInfo">
<h3>ID: <span id="nodeId">unknown</span></h3>
<h3>Discovered Peers: <span id="discoveredPeerCount">0</span></h3>
<h3>Connected Peers: <span id="connectedPeerCount">0</span></h3>
<ul id="connectedPeersList"></ul>
</div>

<hr />

<h2>Some suggestions</h2>

<p>Try adding a new file:</p>

<pre><code class="language-javascript">
async function addFile () {
const textEncoder = new TextEncoder()
const cid = await heliaFs.addFile({content: textEncoder.encode('Hello world!')})
console.log('successfully stored', cid.toString())
}
await addFile()
</code></pre>

<p>
You can cat that same file. If you used the exact same string as above
('Hello world!') you should have an hash like this:
'bafkreigaknpexyvxt76zgkitavbwx6ejgfheup5oybpm77f3pxzrvwpfdi'
</p>

<pre><code class="language-javascript">
async function catFile () {
const textDecoder = new TextDecoder()
for await (const data of heliaFs.cat('bafkreigaknpexyvxt76zgkitavbwx6ejgfheup5oybpm77f3pxzrvwpfdi')) {
console.log(textDecoder.decode(data))
}
}
await catFile()
</code></pre>

<p>
Display the multiaddrs of the peers you've discovered:
</p>
<pre><code class="language-javascript">
for (const [peerIdString, peer] of discoveredPeers.entries()) {
console.log(`${peerIdString}: ${peer.multiaddrs.toString()}`)
}
</code></pre>

<p>
Provide the CIDs you create (once you're connected to a peer)
</p>
<pre><code class="language-javascript">
const textEncoder = new TextEncoder()
const cid = await heliaFs.addFile({content: textEncoder.encode('Hello world!')})
for await (const event of helia.libp2p.dht.provide(cid)) {
console.log(event)
}
</code></pre>

<hr />
<h2>Event Log:</h2>
<article id="runningLog"></article>
</body>
<style>
#runningLog span {
display: block;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-core.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/autoloader/prism-autoloader.min.js" defer></script>
<script src="https://unpkg.com/helia@0.0.0-42308c0/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@helia/unixfs@1.1.0/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/libp2p@0.42.2/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@chainsafe/libp2p-yamux@3.0.7/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@libp2p/mplex@7.1.1/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@libp2p/websockets@5.0.5/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@libp2p/bootstrap@6.0.0/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/blockstore-core@4.0.1/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/datastore-core@9.0.3/dist/index.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@libp2p/kad-dht@8.0.0/dist/index.min.js" defer></script>
<script src="./src/index.js" type="module" defer></script>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since we already have a module loading, I am wondering if importing the dependencies in module would serve the same purpose.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea.. but the example is script tag, so I wanted to focus on that.. as... odd as it is. But this is a good test for the future to ensure that the libraries are importable like this. I've already found a few bugs where the documented window.<object> was different than what the actual result is.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remember that this is an example for a specific usecase. The only goals (AFAIK) are:

  1. to provide a starter template for users who need to use this method for one reason or another
  2. to provide a testable artifact to prove that our libraries work, and continue to work, for these examples given future changes.

@BigLep @achingbrain are there other goals that I'm missing? should we add this to the helia-examples root README.md?

<script nomodule>
alert('Your browser does not support importing ESM modules')
</script>
</html>
30 changes: 30 additions & 0 deletions examples/helia-script-tag/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "example-browser-script-tag",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Using IPFS in the browser via a script tag",
"keywords": [],
"license": "MIT",
"scripts": {
"clean": "rimraf ./dist ./.cache ./node_modules/.vite",
"build": "vite build",
"serve": "vite dev --port 8888",
"start": "npm run serve",
"test": "npm run build && playwright test tests"
},
"browserslist": "last 1 Chrome version",
"devDependencies": {
"@babel/core": "^7.14.8",
"@playwright/test": "^1.12.3",
"playwright": "^1.12.3",
"process": "^0.11.10",
"rimraf": "^3.0.2",
"test-util-ipfs-example": "^1.0.2",
"util": "^0.12.4",
"vite": "^3.1.0"
},
"dependencies": {
"@chainsafe/libp2p-noise": "^11.0.1"
}
}
Loading