Skip to content

Commit

Permalink
First version
Browse files Browse the repository at this point in the history
  • Loading branch information
pagoru committed Mar 18, 2024
1 parent c3ffd89 commit 6ff5a03
Show file tree
Hide file tree
Showing 13 changed files with 663 additions and 676 deletions.
36 changes: 36 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: Publish
on:
push:
tags:
- '*'

jobs:
publish:
runs-on: ubuntu-latest

permissions:
contents: read
id-token: write

steps:
- uses: actions/checkout@v4

- name: Set Versions
uses: actions/github-script@v4
id: set_version
with:
script: |
const tag = context.ref.substring(10).replace('v', '')
core.setOutput('tag', tag)
- name: Add version to package.json
uses: jaywcjlove/github-action-package@main
with:
path: './deno.json'
data: |
{
"version": "${{ steps.set_version.outputs.tag }}"
}
- name: Publish package
run: npx jsr publish
93 changes: 1 addition & 92 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,92 +1 @@
# Deno Web Serve

Template repo with this structure:
https://github.com/pagoru/deno-web-serve-template

### File structure

- /.env
- /dev.ts
- /main.ts
- /public/index.html
- /public/assets/...
- /src/main.tsx

#### .env

```env
ENVIRONMENT=DEVELOPMENT
```

#### dev.ts

```ts
import { load } from "deno/dotenv/mod.ts";

const env = await load();
Object.keys(env).forEach((key) => Deno.env.set(key, env[key]));

await import("./main.ts");
```

#### main.ts

```ts
import { webServe } from "deno_web_serve/mod.ts";

await webServe({
port: 8080,
indexFileName: "main.tsx",
minify: false,
externals: [],
envs: ["ENVIRONMENT"],
mixAllInsideIndex: false,
});
```

#### build.ts

```ts
import { build } from "deno_web_serve";
import { load } from "deno/dotenv/mod.ts";

const env = await load();
Object.keys(env).forEach((key) => Deno.env.set(key, env[key]));

await build({
indexFileName: "main.ts",
minify: true,
mixAllInsideIndex: true,
envs: ["ENVIRONMENT"],
});
```

#### deno.json

```json
{
"tasks": {
"start": "deno run -A ./dev.ts",
"build": "deno run -A ./build.ts"
},
"imports": {
"deno/": "https://deno.land/[email protected]/",
"deno_web_serve": "https://deno.land/x/[email protected]/mod.ts"
}
}
```

#### /public/index.html

```html
<html>
<head>
...
<!-- STYLES_FILE -->
</head>
...
<!-- SCRIPT_ENVS -->
<!-- SCRIPT_BUNDLE -->
<!-- SCRIPT_FOOTER -->
</html>
```
# Game Serve
16 changes: 16 additions & 0 deletions build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { build } from 'deno_web_serve';
import { load } from 'deno/dotenv/mod.ts';


export const buildGame = async () => {
const env = await load();
Object.keys(env).forEach(key => Deno.env.set(key, env[key]));

await build({
indexFileName: 'main.ts',
minify: true,
bundleAssets: true,
envs: [],
});

}
114 changes: 114 additions & 0 deletions debug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { serve } from 'https://deno.land/[email protected]/http/server.ts';
import {
getCurrentDate,
getCurrentFilePath,
BUILD_FOLDER,
} from './src/utils.ts';

export const serveGame = async () => {
const PORT = 8080;

const socketList: (WebSocket | undefined)[] = [];

const sendMessageToClients = (data: any) => {
const socketClientList = socketList.filter(
(ws?: WebSocket) => ws && ws?.readyState === ws.OPEN,
);
console.log(
`[${getCurrentDate()}] Sending changes to clients (${
socketClientList.length
})`,
);
socketClientList.forEach((ws: WebSocket) => ws.send(JSON.stringify(data)));
};

{
const command = new Deno.Command(Deno.execPath(), {
args: [
'run',
'-A',
'--watch=./src',
getCurrentFilePath('debug-bundler.ts'),
],
});
command.spawn();
}

let swapFileMap = {};

await serve(
async (request: Request) => {
if (request.headers.get('upgrade') === 'websocket') {
const { socket: ws, response } = Deno.upgradeWebSocket(request);
socketList.push(ws);
return response;
}

const url = new URL(request.url);
const filepath = url.pathname ? decodeURIComponent(url.pathname) : '';

switch (filepath) {
case '/_reloadBundler':
sendMessageToClients({ type: 'reload' });
return new Response();
case '/_hotSwap':
const reader = request.body.getReader();
let text = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const decoder = new TextDecoder();
const chunkText = decoder.decode(value);

text += chunkText;
}

const list = JSON.parse(text);
for (const { name, mtime, fileData } of list)
swapFileMap[name + mtime] = fileData;

sendMessageToClients({
type: 'hotSwap',
data: list.map(({ name, mtime, globalReference }) => ({
name,
mtime,
globalReference,
})),
});
return new Response();
default:
try {
const path = BUILD_FOLDER + filepath;
const stat = await Deno.stat(path);
if (!stat.isFile) throw '';

const file = await Deno.open(path, {
read: true,
});
return new Response(file?.readable);
} catch (_) {
// ignore
}
}

if (filepath.indexOf('/swapFile') === 0) {
const fileName = filepath.split('/')[2];

return new Response(swapFileMap[fileName], {
headers: {
'content-type': 'application/js',
},
});
}

const indexFileText = await Deno.readTextFile('build/index.html');

return new Response(indexFileText, {
headers: {
'content-type': 'text/html',
},
});
},
{ port: PORT },
);
};
10 changes: 10 additions & 0 deletions deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "@darkaqua/game-serve",
"version": "0.0.0",
"imports": {
"deno/": "https://deno.land/[email protected]/",
"deno_web_serve": "https://deno.land/x/[email protected]/mod.ts"
},
"lock": false,
"nodeModulesDir": true
}
3 changes: 2 additions & 1 deletion mod.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./src/serve.ts";
export * from "./debug.ts";
export * from "./build.ts";
Loading

0 comments on commit 6ff5a03

Please sign in to comment.