typedserver/ts/classes.typedserver.ts

246 lines
7.3 KiB
TypeScript
Raw Normal View History

2024-02-20 16:30:46 +00:00
import * as plugins from './plugins.js';
2024-05-14 13:28:09 +00:00
import * as paths from './paths.js';
2024-05-11 10:51:20 +00:00
import * as interfaces from '../dist_ts_interfaces/index.js';
2023-03-30 13:15:48 +00:00
import * as servertools from './servertools/index.js';
2024-01-09 09:21:01 +00:00
import { type TCompressionMethod } from './servertools/classes.compressor.js';
2023-03-29 12:54:07 +00:00
2023-03-30 13:15:48 +00:00
export interface IServerOptions {
/**
* serve a particular directory
*/
serveDir?: string;
/**
* inject a reload script that takes care of live reloading
*/
injectReload?: boolean;
2024-01-09 09:21:01 +00:00
/**
* enable compression
*/
enableCompression?: boolean;
/**
* choose a preferred compression method
*/
preferredCompressionMethod?: TCompressionMethod;
2023-03-30 13:15:48 +00:00
/**
* watch the serve directory?
*/
2023-03-29 12:54:07 +00:00
watch?: boolean;
2023-03-30 13:15:48 +00:00
cors: boolean;
/**
* a default answer given in case there is no other handler.
* @returns
*/
defaultAnswer?: () => Promise<string>;
/**
* will try to reroute traffic to an ssl connection using headers
*/
forceSsl?: boolean;
/**
* allows serving manifests
*/
manifest?: plugins.smartmanifest.ISmartManifestConstructorOptions;
/**
* the port to listen on
* can be overwritten when actually starting the server
*/
port?: number | string;
publicKey?: string;
privateKey?: string;
sitemap?: boolean;
feed?: boolean;
robots?: boolean;
domain?: string;
/**
* convey information about the app being served
*/
appVersion?: string;
feedMetadata?: plugins.smartfeed.IFeedOptions;
articleGetterFunction?: () => Promise<plugins.tsclass.content.IArticle[]>;
blockWaybackMachine?: boolean;
2023-03-29 12:54:07 +00:00
}
export class TypedServer {
// static
// nothing here yet
// instance
2023-03-30 13:15:48 +00:00
public options: IServerOptions;
2023-03-30 15:44:10 +00:00
public server: servertools.Server;
2023-03-29 12:54:07 +00:00
public smartchokInstance: plugins.smartchok.Smartchok;
public serveDirHashSubject = new plugins.smartrx.rxjs.ReplaySubject<string>(1);
public serveHash: string = '000000';
public typedsocket: plugins.typedsocket.TypedSocket;
public typedrouter = new plugins.typedrequest.TypedRouter();
public lastReload: number = Date.now();
public ended = false;
2023-03-30 13:15:48 +00:00
constructor(optionsArg: IServerOptions) {
const standardOptions: IServerOptions = {
2023-03-29 12:54:07 +00:00
port: 3000,
2023-03-30 17:42:55 +00:00
injectReload: false,
2023-03-30 17:40:41 +00:00
serveDir: null,
watch: false,
2023-03-30 13:15:48 +00:00
cors: true,
2023-03-29 12:54:07 +00:00
};
this.options = {
...standardOptions,
...optionsArg,
};
2023-03-30 17:40:41 +00:00
2023-03-30 15:44:10 +00:00
this.server = new servertools.Server(this.options);
2023-03-29 12:54:07 +00:00
// add routes to the smartexpress instance
2023-03-30 15:44:10 +00:00
this.server.addRoute(
2023-03-29 12:54:07 +00:00
'/typedserver/:request',
2023-03-30 13:15:48 +00:00
new servertools.Handler('ALL', async (req, res) => {
2023-03-29 12:54:07 +00:00
switch (req.params.request) {
case 'devtools':
res.setHeader('Content-Type', 'text/javascript');
res.status(200);
2024-05-14 13:28:09 +00:00
res.write(plugins.smartfile.fs.toStringSync(paths.injectBundlePath));
2023-03-29 12:54:07 +00:00
res.end();
break;
case 'reloadcheck':
console.log('got request for reloadcheck');
res.setHeader('Content-Type', 'text/plain');
res.status(200);
if (this.ended) {
res.write('end');
res.end();
return;
}
res.write(this.lastReload.toString());
res.end();
}
})
);
2023-08-03 18:45:09 +00:00
this.server.addRoute(
'/typedrequest',
new servertools.HandlerTypedRouter(this.typedrouter)
)
2023-03-30 15:44:10 +00:00
}
2023-03-29 12:54:07 +00:00
2023-03-30 15:44:10 +00:00
/**
* inits and starts the server
*/
public async start() {
2023-07-01 10:29:35 +00:00
if (this.options.serveDir) {
2023-03-30 15:44:10 +00:00
this.server.addRoute(
'/*',
new servertools.HandlerStatic(this.options.serveDir, {
responseModifier: async (responseArg) => {
2024-01-07 13:50:14 +00:00
let fileString = responseArg.responseContent.toString();
2023-03-30 15:44:10 +00:00
if (plugins.path.parse(responseArg.path).ext === '.html') {
const fileStringArray = fileString.split('<head>');
if (this.options.injectReload && fileStringArray.length === 2) {
fileStringArray[0] = `${fileStringArray[0]}<head>
<!-- injected by @apiglobal/typedserver start -->
<script async defer type="module" src="/typedserver/devtools"></script>
<script>
globalThis.typedserver = {
2023-04-09 22:55:16 +00:00
lastReload: ${this.lastReload},
2023-03-30 15:44:10 +00:00
versionInfo: ${JSON.stringify({}, null, 2)},
}
</script>
<!-- injected by @apiglobal/typedserver stop -->
`;
fileString = fileStringArray.join('');
console.log('injected typedserver script.');
} else if (this.options.injectReload) {
console.log('Could not insert typedserver script');
}
2023-03-29 12:54:07 +00:00
}
2023-03-30 15:44:10 +00:00
const headers = responseArg.headers;
headers.appHash = this.serveHash;
headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
headers['Pragma'] = 'no-cache';
headers['Expires'] = '0';
return {
headers,
path: responseArg.path,
2024-01-07 13:50:14 +00:00
responseContent: Buffer.from(fileString),
2023-03-30 15:44:10 +00:00
};
},
serveIndexHtmlDefault: true,
2024-01-09 09:21:01 +00:00
enableCompression: this.options.enableCompression,
preferredCompressionMethod: this.options.preferredCompressionMethod,
2023-03-30 15:44:10 +00:00
})
);
} else if (this.options.injectReload) {
2023-07-01 10:29:35 +00:00
throw new Error(
'You set to inject the reload script without a serve dir. This is not supported at the moment.'
);
2023-03-30 15:44:10 +00:00
}
if (this.options.watch && this.options.serveDir) {
2024-02-21 00:06:52 +00:00
this.smartchokInstance = new plugins.smartchok.Smartchok([this.options.serveDir]);
2023-03-29 12:54:07 +00:00
await this.smartchokInstance.start();
(await this.smartchokInstance.getObservableFor('change')).subscribe(async () => {
await this.createServeDirHash();
this.reload();
});
2023-03-30 15:44:10 +00:00
await this.createServeDirHash();
2023-03-29 12:54:07 +00:00
}
// lets start the server
2023-03-30 15:44:10 +00:00
await this.server.start();
2023-03-29 12:54:07 +00:00
this.typedsocket = await plugins.typedsocket.TypedSocket.createServer(
this.typedrouter,
2023-03-30 15:44:10 +00:00
this.server
2023-03-29 12:54:07 +00:00
);
2023-03-31 11:18:23 +00:00
// lets setup typedrouter
2023-07-01 10:29:35 +00:00
this.typedrouter.addTypedHandler<interfaces.IReq_GetLatestServerChangeTime>(
new plugins.typedrequest.TypedHandler('getLatestServerChangeTime', async (reqDataArg) => {
return {
time: this.lastReload,
};
})
);
2023-03-31 11:18:23 +00:00
2023-03-30 15:44:10 +00:00
// console.log('open url in browser');
2023-03-29 12:54:07 +00:00
// await plugins.smartopen.openUrl(`http://testing.git.zone:${this.options.port}`);
}
/**
* reloads the page
*/
public async reload() {
this.lastReload = Date.now();
2023-07-01 10:29:35 +00:00
for (const connectionArg of await this.typedsocket.findAllTargetConnectionsByTag(
'typedserver_frontend'
)) {
2023-03-29 12:54:07 +00:00
const pushTime =
this.typedsocket.createTypedRequest<interfaces.IReq_PushLatestServerChangeTime>(
'pushLatestServerChangeTime',
connectionArg
);
pushTime.fire({
time: this.lastReload,
});
}
}
public async stop() {
this.ended = true;
2023-03-30 15:44:10 +00:00
await this.server.stop();
2023-03-29 12:54:07 +00:00
await this.typedsocket.stop();
2023-03-30 17:44:44 +00:00
if (this.smartchokInstance) {
await this.smartchokInstance.stop();
}
2023-03-29 12:54:07 +00:00
}
public async createServeDirHash() {
const serveDirHash = await plugins.smartfile.fs.fileTreeToHash(this.options.serveDir, '**/*');
this.serveHash = serveDirHash;
console.log('Current ServeDir hash: ' + serveDirHash);
this.serveDirHashSubject.next(serveDirHash);
}
}