Skip to content

Commit

Permalink
feat: enable ipv4 in dev server
Browse files Browse the repository at this point in the history
  • Loading branch information
buttercubz committed Jun 20, 2021
1 parent 7ba6547 commit 51764ac
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 38 deletions.
4 changes: 2 additions & 2 deletions compiler/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export async function RollupBuild({
generate = "dom",
plugins = [],
production = false,
ipv4,
}: RollupBuildProps) {
const base = toFileUrl(Deno.cwd()).href;

Expand All @@ -35,7 +36,6 @@ export async function RollupBuild({
maps: "./import_map.json",
}),
...plugins,
(await DevServer())!,
Svelte({ generate }),
postcss(),
terser(),
Expand All @@ -45,7 +45,7 @@ export async function RollupBuild({
maps: "./import_map.json",
}),
...plugins,
(await DevServer())!,
(await DevServer(ipv4))!,
Svelte({ generate, dev: true }),
postcss(),
];
Expand Down
1 change: 1 addition & 0 deletions compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,5 @@ export interface RollupBuildProps {
generate?: "dom" | "ssg" | "ssr";
plugins?: Plugin[];
production?: boolean;
ipv4?: string;
}
5 changes: 4 additions & 1 deletion src/cli/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default async function StartDev() {
.split(Deno.build.os === "windows" ? "\\" : "/")
.pop()!;

const ip = await ipv4(port);
const { str: ip, ipv4: ipV4 } = await ipv4(port);
const localNet = ip
? `${colors.bold("On Your Network:")} ${ip}:${colors.bold(port.toString())}`
: "";
Expand All @@ -37,6 +37,7 @@ export default async function StartDev() {
dir: outDir,
generate: mode,
plugins,
ipv4: ipV4!,
});

if (mode === "ssg" || mode === "ssr") {
Expand All @@ -51,6 +52,7 @@ export default async function StartDev() {
plugins,
dirName,
localNet,
ipv4: ipV4!,
});
}

Expand Down Expand Up @@ -83,6 +85,7 @@ export default async function StartDev() {
dir: outDir,
generate: mode,
plugins,
ipv4: ipV4!,
});
});
}
Expand Down
21 changes: 9 additions & 12 deletions src/dev_server/hotReloadingClient.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
export default () => {
export default (__SNEL__HOST__) => {
const __SNEL__HOT__PORT__ = Number(window.location.port) + 1;

if ("WebSocket" in window) {
const socket = new WebSocket(`ws://localhost:${__SNEL__HOT__PORT__}`);
const socket = new WebSocket(
`ws://${__SNEL__HOST__}:${__SNEL__HOT__PORT__}`
);

const css = `p code{border-radius:2px;background-color:#eee;color:#111}#editing,#highlighting{margin:10px;padding:10px;border:0;width:calc(100% - 32px);height:150px}#editing,#highlighting,#highlighting *{font-size:15pt;font-family:monospace;line-height:20pt}#editing,#highlighting{position:absolute;top:0;left:0}#editing{z-index:1}#highlighting{z-index:0}#editing{color:transparent;background:transparent;caret-color:white}#editing,#highlighting{overflow:auto}#editing{resize:none}code[class*="language-"],pre[class*="language-"]{font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*="language-"]{padding:.4em .8em;margin:.5em 0;overflow:auto;background:#242829;border-radius:5px}code[class*="language-"]{background:#242829;color:white}:not(pre)>code[class*="language-"]{padding:.2em;border-radius:.3em;box-shadow:none;white-space:normal}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:#aaa}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.property,.token.tag,.token.boolean,.token.number,.token.constant,.token.symbol{color:#0cf}.token.selector,.token.attr-name,.token.string,.token.char,.token.builtin{color:yellow}.token.operator,.token.entity,.token.url,.language-css .token.string,.token.variable,.token.inserted{color:yellowgreen}.token.atrule,.token.attr-value,.token.keyword{color:deeppink}.token.regex,.token.important{color:orange}.token.important,.token.bold{font-weight:bold}.token.italic{font-style:italic}.token.entity{cursor:help}.token.deleted{color:red}pre.diff-highlight.diff-highlight>code .token.deleted:not(.prefix),pre>code.diff-highlight.diff-highlight .token.deleted:not(.prefix){background-color:rgba(255,0,0,0.3);display:inline}pre.diff-highlight.diff-highlight>code .token.inserted:not(.prefix),pre>code.diff-highlight.diff-highlight .token.inserted:not(.prefix){background-color:rgba(0,255,128,0.3);display:inline}`;

Expand Down Expand Up @@ -69,15 +71,8 @@ export default () => {
"background:transparent"
);
} else {
const {
type,
message,
file,
filepath,
code,
errorName,
start,
} = JSON.parse(JSON.parse(event.data).message);
const { type, message, file, filepath, code, errorName, start } =
JSON.parse(JSON.parse(event.data).message);

const styles = document.createElement("style");
styles.innerText = css;
Expand All @@ -95,7 +90,9 @@ export default () => {
</h1>
<hr />
<div>
<span>/${file.split("/").pop()}: ${message.toString()} ( ${start?.line}:${start?.column} )</span>
<span>/${file.split("/").pop()}: ${message.toString()} ( ${
start?.line
}:${start?.column} )</span>
<br />
</div>
<br>
Expand Down
4 changes: 3 additions & 1 deletion src/dev_server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface ServeOptions<T = unknown> {
verbose: boolean;
open: boolean;
historyApiFallback?: string | boolean;
ipv4?: string;
}

export type Defined<T> = Exclude<T, undefined>;
Expand Down Expand Up @@ -60,6 +61,7 @@ class BuildServer {
defaultType: "text/plain",
verbose: true,
onListening() {},
ipv4: undefined,
};

server: Server;
Expand Down Expand Up @@ -97,7 +99,7 @@ class BuildServer {
headers.set("Content-Type", "application/javascript");

const response: Response = {
body: `(${HotClient.toString()})()`,
body: `(${HotClient.toString()})("${this.options.ipv4 ?? "localhost"}")`,
headers,
}

Expand Down
4 changes: 2 additions & 2 deletions src/server_side/BuilderWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Application } from "./imports/oak.ts";
import { htmlBody } from "./templates.ts";

self.onmessage = async (event) => {
const { port, clientPath, path, mode, start, end } = event.data;
const { port, clientPath, path, mode, start, end, ipv4 } = event.data;

const serverSide = new Application();
const controller = new AbortController();
Expand All @@ -31,7 +31,7 @@ self.onmessage = async (event) => {
} if (request.url.pathname === "/__SNEL__HOT__RELOADING.js") {
response.headers.set("content-type", "application/javascript");

const client = `(${ClientHot.toString()})();`
const client = `(${ClientHot.toString()})("${(ipv4) ?? "localhost" }");`

response.status = 200;
response.body = client;
Expand Down
6 changes: 4 additions & 2 deletions src/server_side/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ export async function DevServer({
outDir,
plugins,
dirName,
localNet
localNet,
ipv4
}: DevServerProps) {

const compiler = new Worker(
Expand All @@ -144,7 +145,8 @@ export async function DevServer({
port: Number(port),
path,
mode,
start: true
start: true,
ipv4
});

serverLog({ port, dirName, localNet });
Expand Down
1 change: 1 addition & 0 deletions src/server_side/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ export interface DevServerProps extends Omit<ServerProps, "dist">{
plugins: Plugin[];
dirName: string;
localNet: string;
ipv4?: string;
}
3 changes: 2 additions & 1 deletion src/shared/internal_plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export { terser } from "https://deno.land/x/[email protected]+0.18.2/plugins/terser
export { default as Svelte } from "./bundler.js";
export * from "./import_map.ts";

export async function DevServer() {
export async function DevServer(ipv4?: string) {
const { port, mode } = await loadConfig<snelConfig>(
await resolverConfigFile()
)!;
Expand All @@ -28,6 +28,7 @@ export async function DevServer() {
host: "0.0.0.0",
verbose: false,
historyApiFallback: true,
ipv4,
});
} catch (error) {
if (!(error instanceof Deno.errors.AddrInUse)) {
Expand Down
38 changes: 21 additions & 17 deletions src/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,16 @@ export async function getIP() {
export async function ipv4(port: string | number) {
const ipv4 = await getIP()!;

return ipv4?.split(" ").length === 1
? `http://${ipv4}`
: ipv4
?.split(" ")
.map((ip) => `http://${ip}:${port}`)
.join(" or ");
return {
str:
ipv4?.split(" ").length === 1
? `http://${ipv4}`
: ipv4
?.split(" ")
.map((ip) => `http://${ip}:${port}`)
.join(" or "),
ipv4,
};
}

export function showHelp() {
Expand Down Expand Up @@ -209,18 +213,18 @@ export async function resolverConfigFile(): Promise<string> {
const js = await exists("./snel.config.js");

if (js && ts) {
throw new Error(colors.red("you only can have one snel config file, snel.config.js or snel.config.ts")).message;
}

else if (js) {
throw new Error(
colors.red(
"you only can have one snel config file, snel.config.js or snel.config.ts"
)
).message;
} else if (js) {
return "./snel.config.js";
}

else if (ts) {
} else if (ts) {
return "./snel.config.ts";
}

else {
throw new Error(colors.red("can't load snel config file, not found in the root project")).message;
} else {
throw new Error(
colors.red("can't load snel config file, not found in the root project")
).message;
}
}

0 comments on commit 51764ac

Please sign in to comment.