Skip to content

Commit

Permalink
feat: SvelteKit template
Browse files Browse the repository at this point in the history
  • Loading branch information
peterpeterparker committed Nov 11, 2022
1 parent bfc6d82 commit bba8e58
Show file tree
Hide file tree
Showing 34 changed files with 7,046 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ dist/
_MACOSX
.vscode/
target/
*.old.did
*.old.did
.idea
9 changes: 9 additions & 0 deletions svelte/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<p align="left" >
<img width="240" src="./sveltekit-starter/src/frontend/static/logo.png">
</p>

# Svelte Dapp templates

This subdirectory provides access to Svelte dapp samples that run on the Internet Computer platform.

- [SvelteKit starter](./sveltekit-starter/README.md): A prerendered SvelteKit dapp example
15 changes: 15 additions & 0 deletions svelte/sveltekit-starter/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example

# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

src/declarations
20 changes: 20 additions & 0 deletions svelte/sveltekit-starter/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
plugins: ['svelte3', '@typescript-eslint'],
ignorePatterns: ['*.cjs'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
es2017: true,
node: true
}
};
8 changes: 8 additions & 0 deletions svelte/sveltekit-starter/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
1 change: 1 addition & 0 deletions svelte/sveltekit-starter/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
engine-strict=true
15 changes: 15 additions & 0 deletions svelte/sveltekit-starter/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example

# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

.dfx
9 changes: 9 additions & 0 deletions svelte/sveltekit-starter/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"pluginSearchDirs": ["."],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}
115 changes: 115 additions & 0 deletions svelte/sveltekit-starter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<p align="left" >
<img width="240" src="./src/frontend/static/logo.png">
</p>

# SvelteKit Dapp template

This repository is meant to give [SvelteKit](https://kit.svelte.dev/) developers an easy on-ramp to get started with developing decentralized applications (Dapps in short) for the Internet Computer blockchain.

## What is the Internet Computer?

The Internet Computer is a novel blockchain that has the unique capability to serve web content while not requiring the end users to use a browser extension, such as Metamask.

Coupled with super fast execution the Internet Computer provides the worlds first truly user friendly Web 3.0 experience.

## What are canisters?

Dapps on the Internet Computer live in canisters, which are special smart contracts that run WebAssembly, and can respond to regular HTTP requests, among other capabilities.

This repository uses Svelte for the frontend, and can upload it to an `asset` type canister that can host your frontend on the Internet Computer.

## Security Considerations and Security Best Practices

If you base your application on this example, we recommend you familiarize yourself with and adhere to the [Security Best Practices](https://internetcomputer.org/docs/current/references/security/) for developing on the Internet Computer. This example may not implement all the best practices.

For example, the following aspects are particularly relevant for creating frontends:

- [Use a well-audited authentication service and client side IC libraries](https://internetcomputer.org/docs/current/references/security/web-app-development-security-best-practices#use-a-well-audited-authentication-service-and-client-side-ic-libraries)
- [Define security headers including a Content Security Policy (CSP)](https://internetcomputer.org/docs/current/references/security/web-app-development-security-best-practices#define-security-headers-including-a-content-security-policy-csp)
- [Don’t load JavaScript (and other assets) from untrusted domains](https://internetcomputer.org/docs/current/references/security/web-app-development-security-best-practices#dont-load-javascript-and-other-assets-from-untrusted-domains)

## Getting started

Make sure you have [node.js](https://nodejs.org/) installed.

```
git clone https://github.com/dfinity/examples
cd svelte/sveltekit-starter
npm ci
```

## DFX

Install `dfx` by running

```
sh -ci "$(curl -fsSL https://smartcontracts.org/install.sh)"
```

### Start and stop the local replica

Open a new terminal window _in the project directory_, and run the following command to start the local replica. The replica will not start unless `dfx.json` exists in the current directory.

```
dfx start --background
```

When you're done with development, or you're switching to a different dfx project, running

```
dfx stop
```

from the project directory will stop the local replica.

## Build & run the dapp

To build and deploy the project locally run

```
dfx deploy
```

When the process completes you'll have a frontend canister running locally. To find the frontend canister's ID, run

```
dfx canister id frontend
```

It will output something similar to `rno2w-sqaaa-aaaaa-aaacq-cai`. Copy this ID and open it in the browser using `http://<canister ID>localhost:8000`, eg. `http://rno2w-sqaaa-aaaaa-aaacq-cai.localhost:8000`.

## Local development

You can serve the frontend in development mode like you normally develop an app using the command

```
npm run dev
```

it is not necessary to deploy it to the frontend canister during development.

## Deploying to the IC

To host the Svelte app on the IC, you'll need to have some cycles available. Cycles pay for the execution of your app, and they are also needed to create canisters.

You can get $20 worth of cycles for free from the Cycles Faucet, if you have a GitHub account. To claim them, follow [this guide](https://smartcontracts.org/docs/quickstart/cycles-faucet.html).

You should have a canister running the cycles wallet on the IC at this point. The cycles wallet makes it easy to pay for canister creation.

You can check the balance by running

```
dfx wallet --network ic balance
```

After making sure you have cycles available you can run

```
dfx deploy --network ic
```

The command will build the project, create a new canister on the IC and deploy the Svelte app into it. The command will also create a new file `canister_ids.json` which will help the dfx tool deploy to the same canister in future updates. You can commit this file in your repository.

You can now open your Svelte app running on the IC. You can find the canister ID in the deploy command output, or use the ID in `canister_ids.json`.

The link to your app is `<canister_id>.ic0.app`. For example if your canister ID is `zgvi5-hiaaa-aaaam-aaasq-cai`, your app will be at `https://zgvi5-hiaaa-aaaam-aaasq-cai.ic0.app/`.
84 changes: 84 additions & 0 deletions svelte/sveltekit-starter/copy.types.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/env node

import { existsSync, lstatSync, mkdirSync, readdirSync } from 'fs';
import { copyFile, readFile, writeFile } from 'fs/promises';
import { basename, dirname, extname, join } from 'path';

const copyTypes = async ({ src = `.dfx/local/canisters/`, dest = `./src/declarations` }) => {
const promises = readdirSync(src)
.filter((sub) => !['idl'].includes(sub))
.map(
(dir) =>
new Promise(async (resolve) => {
const [srcPath, destPath] = [src, dest].map((dirPath) => join(dirPath, dir));

const stat = lstatSync(srcPath);

if (stat.isDirectory()) {
await copyTypes({ src: srcPath, dest: destPath });
} else if (stat.isFile()) {
await copyDeclarationsFile({ srcPath, destPath });
}

resolve();
})
);

await Promise.all(promises);
};

const copyDeclarationsFile = async ({ srcPath, destPath }) => {
if (!['.did', '.ts', '.js'].includes(extname(srcPath))) {
return;
}

if (extname(srcPath) === '.mjs') {
return;
}

if (basename(srcPath).includes('.old')) {
return;
}

// Create destination directory if does not exists
const dir = dirname(destPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}

await copyFile(srcPath, destPath);
};

/**
* We have to manipulate the types as long as https://github.com/dfinity/sdk/discussions/2761 is not implemented
*/
const cleanTypes = async ({ dest = `./src/declarations` }) => {
const promises = readdirSync(dest).map(
(dir) =>
new Promise(async (resolve) => {
const indexPath = join(dest, dir, 'index.js');

const content = await readFile(indexPath, 'utf-8');
const clean = content
.replace(/export const \w* = createActor\(canisterId\);/g, '')
.replace(/export const canisterId = process\.env\.\w*_CANISTER_ID;/g, '');

await writeFile(indexPath, clean, 'utf-8');

resolve();
})
);

await Promise.all(promises);
};

(async () => {
try {
await copyTypes({});
await cleanTypes({});

console.log(`Types declarations copied!`);
} catch (err) {
console.error(`Error while copying the types declarations.`, err);
}
})();
30 changes: 30 additions & 0 deletions svelte/sveltekit-starter/dfx.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"canisters": {
"backend": {
"main": "src/backend/main.mo",
"type": "motoko"
},
"frontend": {
"dependencies": ["backend"],
"frontend": {
"entrypoint": "build/index.html"
},
"source": ["build/"],
"type": "assets"
}
},
"defaults": {
"build": {
"args": "",
"packtool": ""
}
},
"dfx": "0.11.2",
"networks": {
"local": {
"bind": "127.0.0.1:8000",
"type": "ephemeral"
}
},
"version": 1
}
Loading

0 comments on commit bba8e58

Please sign in to comment.