toiljs 0.0.136 → 0.0.138

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
1
  import { readDeriveCatalog, deriveIdentity } from 'toiljs/io';
2
- import { spawn } from 'node:child_process';
3
2
  import fs from 'node:fs';
4
3
  import { createRequire } from 'node:module';
5
4
  import net from 'node:net';
@@ -15,6 +14,8 @@ import { prerenderStaticParams } from './ssg.js';
15
14
  import { extractDevSsrTemplates, extractServerSlots, extractTemplates, } from './template-build.js';
16
15
  import { createViteConfig } from './vite.js';
17
16
  import { logSecurityDeployment } from './security-deployment.js';
17
+ import { runCompilerPasses } from './compiler-build.js';
18
+ import { withCompilerLock } from './compiler-lock.js';
18
19
  export const SURFACE_DECORATOR = /^[ \t]*@(data|rest|service|remote|stream|daemon|scheduled)\b/m;
19
20
  function toilconfigEntries(root) {
20
21
  try {
@@ -136,6 +137,11 @@ function serverAuthEnabled(root, configAuth) {
136
137
  return serverImportsAuth(root, serverEntryFiles(root));
137
138
  }
138
139
  export async function buildServer(root, auth = false, authRoutes = {}, logging = false) {
140
+ if (!fs.existsSync(path.join(root, 'toilconfig.json')))
141
+ return;
142
+ await withCompilerLock(root, () => buildServerLocked(path.resolve(root), auth, authRoutes, logging));
143
+ }
144
+ async function buildServerLocked(root, auth, authRoutes, logging) {
139
145
  if (!fs.existsSync(path.join(root, 'toilconfig.json')))
140
146
  return;
141
147
  for (const dir of serverDirs(root)) {
@@ -154,7 +160,8 @@ export async function buildServer(root, auth = false, authRoutes = {}, logging =
154
160
  fs.mkdirSync(authLib, { recursive: true });
155
161
  fs.writeFileSync(path.join(authLib, '_auth_routes.ts'), `// Generated by toiljs. Rebuild to change auth route policy.\n` +
156
162
  `@inline export function __toilAuthGoogleEnabled(): bool { return ${authRoutes.google !== false}; }\n` +
157
- `@inline export function __toilAuthTwoFactorSetupEnabled(): bool { return ${authRoutes.twoFactorSetup !== false}; }\n`);
163
+ `@inline export function __toilAuthTwoFactorSetupEnabled(): bool { return ${authRoutes.twoFactorSetup !== false}; }\n` +
164
+ `@inline export function __toilAuthDeleteAccountEnabled(): bool { return ${authRoutes.deleteAccount !== false}; }\n`);
158
165
  const appHasUser = serverDeclaresUser(root, files);
159
166
  const authFiles = authEntryFiles(root, appHasUser);
160
167
  const authSet = new Set(authFiles);
@@ -183,47 +190,58 @@ export async function buildServer(root, auth = false, authRoutes = {}, logging =
183
190
  }
184
191
  if (split.hasDaemon || split.hasStream) {
185
192
  const artifacts = serverArtifacts(root);
193
+ const passes = [];
186
194
  if (split.hasDaemon)
187
- await runToilscriptPass(root, binJs, split.cold, {
195
+ passes.push(toilscriptPass(root, split.cold, {
188
196
  mode: 'cold',
189
197
  outFile: artifacts.cold,
190
198
  withRpc: false,
191
199
  authUser: authOn,
192
200
  logging,
193
- });
201
+ }));
194
202
  if (split.hasStream && split.stream.length > 0)
195
- await runToilscriptPass(root, binJs, split.stream, {
203
+ passes.push(toilscriptPass(root, split.stream, {
196
204
  mode: 'hot',
197
205
  outFile: artifacts.stream,
198
206
  withRpc: false,
199
207
  authUser: authOn,
200
208
  logging,
201
- });
209
+ }));
202
210
  if (split.request.length > 0)
203
- await runToilscriptPass(root, binJs, split.request, {
211
+ passes.push(toilscriptPass(root, split.request, {
204
212
  mode: 'hot',
205
213
  outFile: serverWasmFile(root),
206
214
  withRpc: true,
207
215
  rpcSurfaceFiles: split.hasStream ? split.stream : undefined,
208
216
  authUser: authOn,
209
217
  logging,
210
- });
211
- if (split.request.length > 0)
212
- validateDeriveContinuationArtifacts(fs.readFileSync(serverWasmFile(root)), split.hasDaemon ? fs.readFileSync(artifacts.cold) : null);
213
- if (split.hasDaemon)
214
- validateDeriveContinuationArtifacts(null, fs.readFileSync(artifacts.cold));
215
- if (split.hasStream && split.stream.length > 0)
216
- emitStreamClientSurface(root, artifacts.stream, split.stream);
218
+ }));
219
+ await runCompilerPasses(root, binJs, passes, () => {
220
+ migrateRpcFile(root);
221
+ if (split.hasStream && split.stream.length > 0)
222
+ emitStreamClientSurface(root, artifacts.stream, split.stream);
223
+ }, {
224
+ validate: (readOutput) => {
225
+ if (split.hasDaemon)
226
+ validateDeriveContinuationArtifacts(null, readOutput(artifacts.cold));
227
+ if (split.request.length > 0)
228
+ validateDeriveContinuationArtifacts(readOutput(serverWasmFile(root)), split.hasDaemon ? readOutput(artifacts.cold) : null);
229
+ },
230
+ });
217
231
  return;
218
232
  }
219
- await runToilscriptPass(root, binJs, files, {
233
+ const pass = toilscriptPass(root, files, {
220
234
  mode: 'hot',
221
235
  outFile: null,
222
236
  withRpc: true,
223
237
  authUser: authOn,
224
238
  logging,
225
239
  });
226
- validateDeriveContinuationArtifacts(fs.readFileSync(serverWasmFile(root)), null);
240
+ await runCompilerPasses(root, binJs, [pass], () => {
241
+ migrateRpcFile(root);
242
+ }, {
243
+ validate: (readOutput) => validateDeriveContinuationArtifacts(readOutput(serverWasmFile(root)), null),
244
+ });
227
245
  }
228
246
  export function validateDeriveContinuationArtifacts(hot, cold) {
229
247
  const moduleOf = (bytes) => new WebAssembly.Module(Uint8Array.from(bytes));
@@ -392,8 +410,8 @@ export function assertNoStreamInRequestTier(root, split) {
392
410
  '\nRemove the import, or move the code into a *.stream.ts module.');
393
411
  }
394
412
  }
395
- async function runToilscriptPass(root, binJs, files, opts) {
396
- const args = [binJs, ...files, '--target', 'release'];
413
+ function toilscriptPass(root, files, opts) {
414
+ const args = [...files, '--target', 'release'];
397
415
  const logLib = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../server/globals/toil-log.ts');
398
416
  args.push('--lib', logLib, '--use', 'Log=ToilLog', '--use', `__TOIL_LOGGING=${opts.logging ? '1' : '0'}`);
399
417
  const editorTier = opts.mode === 'cold' ? 'cold' : opts.withRpc ? 'request' : 'stream';
@@ -402,11 +420,21 @@ async function runToilscriptPass(root, binJs, files, opts) {
402
420
  if (opts.mode !== null)
403
421
  args.push('--targetMode', opts.mode);
404
422
  if (opts.mode === 'cold')
405
- args.push('--runtime', 'incremental');
423
+ args.push('--runtime', 'minimal', '--exportRuntime');
406
424
  if (opts.outFile !== null)
407
425
  args.push('--outFile', opts.outFile);
408
426
  if (opts.withRpc)
409
427
  args.push('--rpcModule', 'shared/server.ts');
428
+ else {
429
+ args.push('--rpcModule', '');
430
+ const config = JSON.parse(fs.readFileSync(path.join(root, 'toilconfig.json'), 'utf8'));
431
+ const target = config.targets?.release;
432
+ const text = target?.textFile ?? config.options?.textFile;
433
+ if (text && opts.outFile)
434
+ args.push('--textFile', opts.outFile.replace(/\.[^.]+$/, '') + path.extname(text));
435
+ if ((target?.sourceMap ?? config.options?.sourceMap) && opts.outFile)
436
+ args.push('--sourceMap', path.basename(opts.outFile) + '.map');
437
+ }
410
438
  if (opts.rpcSurfaceFiles)
411
439
  for (const surfaceFile of opts.rpcSurfaceFiles)
412
440
  args.push('--rpcSurfaceFiles', surfaceFile);
@@ -416,22 +444,16 @@ async function runToilscriptPass(root, binJs, files, opts) {
416
444
  args.push('--lib', AUTH_EMAILS_LIB_SUBDIR);
417
445
  args.push('--noConfigEntries');
418
446
  args.push('--disableWarning', '235');
419
- await new Promise((resolve, reject) => {
420
- const child = spawn(process.execPath, args, { cwd: root, stdio: 'inherit' });
421
- child.on('error', reject);
422
- child.on('close', (code) => code === 0
423
- ? resolve()
424
- : reject(new Error(`toilscript ${opts.mode ?? 'release'} build failed (exit ${String(code)})`)));
425
- });
426
- if (opts.withRpc) {
427
- const generated = path.join(root, 'shared/server.ts');
428
- if (fs.existsSync(generated)) {
429
- const source = fs.readFileSync(generated, 'utf8');
430
- const updated = migrateGeneratedRpcClient(source);
431
- if (source !== updated)
432
- fs.writeFileSync(generated, updated);
433
- }
434
- }
447
+ return { name: editorTier, args };
448
+ }
449
+ function migrateRpcFile(root) {
450
+ const generated = path.join(root, 'shared/server.ts');
451
+ if (!fs.existsSync(generated))
452
+ return;
453
+ const source = fs.readFileSync(generated, 'utf8');
454
+ const updated = migrateGeneratedRpcClient(source);
455
+ if (source !== updated)
456
+ fs.writeFileSync(generated, updated);
435
457
  }
436
458
  export function migrateGeneratedRpcClient(source) {
437
459
  return source.replace(/(async function __toilRpcCall\(__id: number, __body: )Uint8Array(?=\))/, '$1Uint8Array<ArrayBuffer>');
@@ -452,9 +474,11 @@ function watchServer(cfg, watcher) {
452
474
  building = true;
453
475
  process.stdout.write(pc.dim(' server changed, rebuilding…') + '\n');
454
476
  const authOn = serverAuthEnabled(root, cfg.auth);
455
- renderEmails(cfg, authOn)
456
- .then(() => renderAuthEmails(cfg, authOn))
457
- .then(() => buildServer(root, cfg.auth, cfg.authRoutes, cfg.logging ?? true))
477
+ withCompilerLock(root, async () => {
478
+ await renderEmails(cfg, authOn);
479
+ await renderAuthEmails(cfg, authOn);
480
+ await buildServerLocked(root, cfg.auth, cfg.authRoutes, cfg.logging ?? true);
481
+ })
458
482
  .then(() => process.stdout.write(pc.green(' ✓ ') + pc.dim('server rebuilt') + '\n'))
459
483
  .catch((e) => process.stdout.write(pc.red(` ✗ server rebuild failed: ${String(e)}`) + '\n'))
460
484
  .finally(() => {
@@ -643,6 +667,9 @@ function isExposedHost(host) {
643
667
  return host !== '127.0.0.1' && host !== 'localhost' && host !== '::1';
644
668
  }
645
669
  export async function dev(opts = {}) {
670
+ return withCompilerLock(path.resolve(opts.root ?? process.cwd()), () => devLocked(opts));
671
+ }
672
+ async function devLocked(opts) {
646
673
  const cfg = await loadConfig(opts);
647
674
  const hasServer = fs.existsSync(path.join(cfg.root, 'toilconfig.json'));
648
675
  if (hasServer)
@@ -653,7 +680,7 @@ export async function dev(opts = {}) {
653
680
  generate(cfg);
654
681
  if (hasServer)
655
682
  await extractServerSlots(cfg);
656
- await buildServer(cfg.root, cfg.auth, cfg.authRoutes, cfg.logging ?? true);
683
+ await buildServerLocked(cfg.root, cfg.auth, cfg.authRoutes, cfg.logging ?? true);
657
684
  if (hasServer)
658
685
  process.stdout.write(pc.green(' ✓ ') + pc.dim('server built') + '\n');
659
686
  if (!hasServer) {
@@ -730,6 +757,9 @@ export async function dev(opts = {}) {
730
757
  return server;
731
758
  }
732
759
  export async function build(opts = {}) {
760
+ await withCompilerLock(path.resolve(opts.root ?? process.cwd()), () => buildLocked(opts));
761
+ }
762
+ async function buildLocked(opts) {
733
763
  const cfg = await loadConfig(opts);
734
764
  const hasServer = fs.existsSync(path.join(cfg.root, 'toilconfig.json'));
735
765
  if (hasServer && !opts.serverOnly)
@@ -739,7 +769,7 @@ export async function build(opts = {}) {
739
769
  await renderAuthEmails(cfg, authOnBuild);
740
770
  generate(cfg);
741
771
  const priorServerSlots = hasServer ? await extractServerSlots(cfg) : new Map();
742
- await buildServer(cfg.root, cfg.auth, cfg.authRoutes, cfg.logging ?? false);
772
+ await buildServerLocked(cfg.root, cfg.auth, cfg.authRoutes, cfg.logging ?? false);
743
773
  if (opts.serverOnly)
744
774
  return;
745
775
  if (hasServer)
@@ -759,7 +789,7 @@ export async function build(opts = {}) {
759
789
  const ssr = await extractTemplates(cfg, 'edge', priorServerSlots);
760
790
  if (ssr.serverSlotsChanged) {
761
791
  process.stdout.write(pc.dim(' SSR template changed; recompiling the server with the new hash…') + '\n');
762
- await buildServer(cfg.root, cfg.auth, cfg.authRoutes, cfg.logging ?? false);
792
+ await buildServerLocked(cfg.root, cfg.auth, cfg.authRoutes, cfg.logging ?? false);
763
793
  }
764
794
  logSecurityDeployment(cfg);
765
795
  }
@@ -985,5 +1015,6 @@ function emitStreamClientSurface(root, streamWasmPath, streamFiles) {
985
1015
  attach +
986
1016
  (typeBlock.length > 0 ? '\n' + typeBlock : '');
987
1017
  fs.mkdirSync(path.dirname(rpcModule), { recursive: true });
988
- fs.writeFileSync(rpcModule, out);
1018
+ if (!fs.existsSync(rpcModule) || fs.readFileSync(rpcModule, 'utf8') !== out)
1019
+ fs.writeFileSync(rpcModule, out);
989
1020
  }
@@ -3,4 +3,5 @@ import { type ResolvedToilConfig } from './config.js';
3
3
  export declare function extractStaticExports(filePath: string, names: readonly string[]): Record<string, Record<string, unknown>>;
4
4
  export declare function extractStaticMetadata(filePath: string): Record<string, unknown> | null;
5
5
  export declare function exportsTrue(filePath: string, name: string): boolean;
6
+ export declare function mayExport(filePath: string, name: string): boolean;
6
7
  export declare function prerenderPlugin(cfg: ResolvedToilConfig): Plugin;
@@ -4,6 +4,16 @@ import { parseSync } from 'oxc-parser';
4
4
  import { patternToBracketFile, scanRoutes, staticSectionPattern } from './routes.js';
5
5
  import { injectSeoHtml, routeSeo } from './seo.js';
6
6
  const UNRESOLVED = Symbol('unresolved');
7
+ function hasCommonJsReference(node) {
8
+ if (Array.isArray(node))
9
+ return node.some(hasCommonJsReference);
10
+ if (node === null || typeof node !== 'object')
11
+ return false;
12
+ const entry = node;
13
+ if (entry.type === 'Identifier' && (entry.name === 'module' || entry.name === 'exports'))
14
+ return true;
15
+ return Object.values(entry).some(hasCommonJsReference);
16
+ }
7
17
  function evalNode(node) {
8
18
  switch (node.type) {
9
19
  case 'Literal':
@@ -112,6 +122,51 @@ export function extractStaticMetadata(filePath) {
112
122
  export function exportsTrue(filePath, name) {
113
123
  return staticExports(filePath, [name])[name] === true;
114
124
  }
125
+ export function mayExport(filePath, name) {
126
+ let source;
127
+ try {
128
+ source = fs.readFileSync(filePath, 'utf8');
129
+ }
130
+ catch {
131
+ return true;
132
+ }
133
+ const parsed = parseSync(filePath, source);
134
+ if (parsed.errors.length)
135
+ return true;
136
+ for (const statement of parsed.program.body) {
137
+ if (statement.type === 'TSExportAssignment')
138
+ return true;
139
+ if (statement.type === 'ExportAllDeclaration') {
140
+ if (!statement.exported)
141
+ return true;
142
+ const exported = statement.exported;
143
+ if (('name' in exported ? exported.name : exported.value) === name)
144
+ return true;
145
+ }
146
+ if (statement.type !== 'ExportNamedDeclaration')
147
+ continue;
148
+ for (const specifier of statement.specifiers) {
149
+ const exported = specifier.exported;
150
+ if (('name' in exported ? exported.name : exported.value) === name)
151
+ return true;
152
+ }
153
+ const declaration = statement.declaration;
154
+ if (declaration?.type === 'VariableDeclaration') {
155
+ for (const entry of declaration.declarations) {
156
+ if (entry.id.type !== 'Identifier' || entry.id.name === name)
157
+ return true;
158
+ }
159
+ }
160
+ else if (declaration &&
161
+ 'id' in declaration &&
162
+ declaration.id &&
163
+ 'name' in declaration.id &&
164
+ declaration.id.name === name) {
165
+ return true;
166
+ }
167
+ }
168
+ return /\b(?:module|exports)\b/.test(source) && hasCommonJsReference(parsed.program);
169
+ }
115
170
  export function prerenderPlugin(cfg) {
116
171
  return {
117
172
  name: 'toil:prerender-seo',
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { createServer } from 'vite';
4
- import { extractStaticMetadata } from './prerender.js';
4
+ import { extractStaticMetadata, mayExport } from './prerender.js';
5
5
  import { scanRoutes } from './routes.js';
6
6
  import { injectSeoHtml, joinUrl, llmsTxt, routeSeo, sitemapXml } from './seo.js';
7
7
  import { createViteConfig } from './vite.js';
@@ -29,7 +29,10 @@ export async function prerenderStaticParams(cfg) {
29
29
  if (!fs.existsSync(shellPath))
30
30
  return [];
31
31
  const allRoutes = scanRoutes(cfg.routesAbsDir);
32
- const dynamic = allRoutes.filter((r) => r.slot === undefined && !r.intercept && /[:*]/.test(r.pattern));
32
+ const dynamic = allRoutes.filter((r) => r.slot === undefined &&
33
+ !r.intercept &&
34
+ /[:*]/.test(r.pattern) &&
35
+ mayExport(r.file, 'generateStaticParams'));
33
36
  if (dynamic.length === 0)
34
37
  return [];
35
38
  const shell = fs.readFileSync(shellPath, 'utf8');
@@ -9,7 +9,7 @@ import { scanRoutes } from './routes.js';
9
9
  import { generateSlotsModule } from './ssr-codegen.js';
10
10
  import { assignSlotIds, coherenceHash, encodeSlots, extractFromHtml, } from './template.js';
11
11
  import { createViteConfig } from './vite.js';
12
- import { extractStaticMetadata } from './prerender.js';
12
+ import { extractStaticMetadata, mayExport } from './prerender.js';
13
13
  import { escapeAttr, escapeHtml, injectSeoHtml, routeSeo } from './seo.js';
14
14
  const SSR_MARKER = '<template id="__toil_ssr"></template>';
15
15
  const ROOT_DIV = '<div id="root"></div>';
@@ -148,7 +148,7 @@ export function writeServerSlotsModules(root, modules) {
148
148
  return written;
149
149
  }
150
150
  async function renderSsrRoutes(cfg, shell) {
151
- const routes = scanRoutes(cfg.routesAbsDir).filter((r) => r.slot === undefined && !r.intercept);
151
+ const routes = scanRoutes(cfg.routesAbsDir).filter((r) => r.slot === undefined && !r.intercept && mayExport(r.file, 'ssr'));
152
152
  if (routes.length === 0)
153
153
  return [];
154
154
  const warn = (msg) => {
@@ -160,16 +160,16 @@ async function renderSsrRoutes(cfg, shell) {
160
160
  appType: 'custom',
161
161
  logLevel: 'silent',
162
162
  });
163
- const client = (await server.ssrLoadModule('toiljs/client'));
164
- const globalsModule = path.join(cfg.toilDir, 'globals.ts');
165
- if (fs.existsSync(globalsModule)) {
166
- await server.ssrLoadModule(globalsModule);
167
- }
168
- const appRequire = createRequire(path.join(cfg.root, 'package.json'));
169
- const react = appRequire('react');
170
- const reactDomServer = appRequire('react-dom/server');
171
163
  const rendered = [];
172
164
  try {
165
+ const client = (await server.ssrLoadModule('toiljs/client'));
166
+ const globalsModule = path.join(cfg.toilDir, 'globals.ts');
167
+ if (fs.existsSync(globalsModule)) {
168
+ await server.ssrLoadModule(globalsModule);
169
+ }
170
+ const appRequire = createRequire(path.join(cfg.root, 'package.json'));
171
+ const react = appRequire('react');
172
+ const reactDomServer = appRequire('react-dom/server');
173
173
  for (const r of routes) {
174
174
  let mod;
175
175
  try {