@spfn/core 0.3.0-beta.2 → 0.3.0-beta.21
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.
- package/README.md +343 -16
- package/dist/app-config/index.d.ts +134 -0
- package/dist/app-config/index.js +58 -0
- package/dist/app-config/index.js.map +1 -0
- package/dist/authz/index.js +1 -381
- package/dist/authz/index.js.map +1 -1
- package/dist/{boss-D16fO2oG.d.ts → boss-BiDCbbAQ.d.ts} +60 -7
- package/dist/codegen/index.d.ts +93 -15
- package/dist/codegen/index.js +626 -165
- package/dist/codegen/index.js.map +1 -1
- package/dist/config/index.d.ts +0 -63
- package/dist/config/index.js +15 -15
- package/dist/config/index.js.map +1 -1
- package/dist/contract/index.d.ts +40 -17
- package/dist/contract/index.js +147 -23
- package/dist/contract/index.js.map +1 -1
- package/dist/db/index.d.ts +201 -34
- package/dist/db/index.js +294 -158
- package/dist/db/index.js.map +1 -1
- package/dist/{define-middleware-DfDP39Nq.d.ts → define-middleware-CVKgqo8S.d.ts} +1 -1
- package/dist/env/index.d.ts +6 -442
- package/dist/env/index.js +13 -16
- package/dist/env/index.js.map +1 -1
- package/dist/env/loader.js +24 -1
- package/dist/env/loader.js.map +1 -1
- package/dist/error-TsUIjp_x.d.ts +157 -0
- package/dist/errors/index.js +1 -381
- package/dist/errors/index.js.map +1 -1
- package/dist/event/index.d.ts +5 -5
- package/dist/event/index.js +32 -1
- package/dist/event/index.js.map +1 -1
- package/dist/event/sse/client.d.ts +18 -4
- package/dist/event/sse/client.js +38 -2
- package/dist/event/sse/client.js.map +1 -1
- package/dist/event/sse/index.d.ts +5 -4
- package/dist/event/ws/client.d.ts +3 -2
- package/dist/event/ws/index.d.ts +4 -3
- package/dist/job/index.d.ts +48 -3
- package/dist/job/index.js +131 -52
- package/dist/job/index.js.map +1 -1
- package/dist/logger/index.js +0 -12
- package/dist/logger/index.js.map +1 -1
- package/dist/middleware/index.d.ts +6 -2
- package/dist/middleware/index.js +7 -388
- package/dist/middleware/index.js.map +1 -1
- package/dist/nextjs/index.d.ts +88 -8
- package/dist/nextjs/index.js +138 -62
- package/dist/nextjs/index.js.map +1 -1
- package/dist/nextjs/server.d.ts +45 -7
- package/dist/nextjs/server.js +14 -0
- package/dist/nextjs/server.js.map +1 -1
- package/dist/ops/index.d.ts +62 -43
- package/dist/ops/index.js +638 -97
- package/dist/ops/index.js.map +1 -1
- package/dist/registry-C2KQCh0m.d.ts +473 -0
- package/dist/route/index.d.ts +6 -3
- package/dist/route/index.js +97 -28
- package/dist/route/index.js.map +1 -1
- package/dist/route/types.d.ts +7 -1
- package/dist/{router-Qbssr11H.d.ts → route-builder-DRW-MSCJ.d.ts} +52 -127
- package/dist/router-4YoIy5fN.d.ts +172 -0
- package/dist/{token-manager-BT5EnUAR.d.ts → router-CysBmgv3.d.ts} +81 -127
- package/dist/server/index.d.ts +185 -14
- package/dist/server/index.js +883 -78
- package/dist/server/index.js.map +1 -1
- package/dist/surface/index.d.ts +115 -0
- package/dist/surface/index.js +1003 -0
- package/dist/surface/index.js.map +1 -0
- package/dist/token-manager-Ckjt2-qq.d.ts +122 -0
- package/dist/{types-D1c57Ko-.d.ts → types-5Rl11_Nb.d.ts} +43 -4
- package/dist/{types-ZQODsBft.d.ts → types-B8zAxFsE.d.ts} +2 -1
- package/dist/types-CxhPH4s_.d.ts +375 -0
- package/dist/{types-2AbaW4Ie.d.ts → types-W4u_S0lF.d.ts} +4 -3
- package/docs/file-upload.md +195 -333
- package/package.json +20 -9
- package/src/cache/README.md +330 -0
- package/src/codegen/README.md +634 -0
- package/src/config/README.md +333 -0
- package/src/contract/README.md +440 -0
- package/src/db/README.md +589 -0
- package/src/db/manager/README.md +500 -0
- package/src/db/schema/README.md +354 -0
- package/src/db/transaction/README.md +822 -0
- package/src/env/README.md +787 -0
- package/src/errors/README.md +429 -0
- package/src/event/README.md +789 -0
- package/src/job/README.md +613 -0
- package/src/logger/README.md +321 -0
- package/src/middleware/README.md +634 -0
- package/src/nextjs/README.md +688 -0
- package/src/route/README.md +763 -0
- package/src/security/README.md +100 -0
- package/src/server/README.md +704 -0
- package/dist/types-9oszaJqp.d.ts +0 -250
package/dist/codegen/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { watch } from 'chokidar';
|
|
2
|
-
import { join, relative, sep, dirname, resolve } from 'path';
|
|
2
|
+
import { join, relative, sep, dirname, resolve, isAbsolute } from 'path';
|
|
3
3
|
import mm from 'micromatch';
|
|
4
4
|
import { logger } from '@spfn/core/logger';
|
|
5
|
-
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
|
|
5
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync, statSync, readdirSync } from 'fs';
|
|
6
6
|
import { createJiti } from 'jiti';
|
|
7
|
+
import { createRequire } from 'module';
|
|
7
8
|
import { collectContractDocument, writeCurrentDocument, checkContract, formatViolations } from '@spfn/core/contract';
|
|
8
9
|
|
|
9
10
|
// src/codegen/core/orchestrator.ts
|
|
@@ -334,70 +335,550 @@ async function createGeneratorsFromConfig(config, cwd) {
|
|
|
334
335
|
}
|
|
335
336
|
return generators2;
|
|
336
337
|
}
|
|
337
|
-
var
|
|
338
|
-
function
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
338
|
+
var compiler;
|
|
339
|
+
function typescript() {
|
|
340
|
+
compiler ??= createRequire(import.meta.url)("typescript");
|
|
341
|
+
return compiler;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/codegen/generators/contract-guard.ts
|
|
345
|
+
var ConditionalRegistrationError = class extends Error {
|
|
346
|
+
constructor(message) {
|
|
347
|
+
super(message);
|
|
348
|
+
this.name = "ConditionalRegistrationError";
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
var REFUSAL_WORDING = {
|
|
352
|
+
defineRouter: {
|
|
353
|
+
noun: "routes",
|
|
354
|
+
consequence: "a route production registers is left out, and the client that addresses it by name gets a 404",
|
|
355
|
+
remedy: "Register the route unconditionally and gate its behaviour inside the handler instead."
|
|
356
|
+
},
|
|
357
|
+
defineEventRouter: {
|
|
358
|
+
noun: "events",
|
|
359
|
+
consequence: "an event production streams is left out, and the client that subscribes to it by name gets a 400",
|
|
360
|
+
remedy: "Register the event unconditionally and decide who receives it with the stream's authorize hook instead."
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
function assertUnconditionalRegistration(scan) {
|
|
364
|
+
const compiler2 = typescript();
|
|
365
|
+
const file = compiler2.createSourceFile(
|
|
366
|
+
scan.routerPath,
|
|
367
|
+
scan.source,
|
|
368
|
+
compiler2.ScriptTarget.Latest,
|
|
369
|
+
/* setParentNodes */
|
|
370
|
+
false
|
|
371
|
+
);
|
|
372
|
+
const declarations = topLevelInitialisers(compiler2, file);
|
|
373
|
+
const routes = routesLiteral(compiler2, declarations.get(scan.exportName), declarations, /* @__PURE__ */ new Set(), factoryOf(scan));
|
|
374
|
+
if (routes) {
|
|
375
|
+
assertLiteral(compiler2, file, routes, declarations, /* @__PURE__ */ new Set(), scan);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
function factoryOf(scan) {
|
|
379
|
+
return scan.factory ?? "defineRouter";
|
|
380
|
+
}
|
|
381
|
+
function topLevelInitialisers(compiler2, file) {
|
|
382
|
+
const found = /* @__PURE__ */ new Map();
|
|
383
|
+
for (const statement of file.statements) {
|
|
384
|
+
if (compiler2.isExportAssignment(statement) && !statement.isExportEquals) {
|
|
385
|
+
found.set("default", statement.expression);
|
|
386
|
+
}
|
|
387
|
+
if (compiler2.isVariableStatement(statement)) {
|
|
388
|
+
collectDeclarations(compiler2, statement, found);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
for (const statement of file.statements) {
|
|
392
|
+
collectRenamedExports(compiler2, statement, found);
|
|
393
|
+
}
|
|
394
|
+
return found;
|
|
395
|
+
}
|
|
396
|
+
function collectDeclarations(compiler2, statement, found) {
|
|
397
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
398
|
+
if (compiler2.isIdentifier(declaration.name) && declaration.initializer) {
|
|
399
|
+
found.set(declaration.name.text, declaration.initializer);
|
|
352
400
|
}
|
|
353
|
-
} catch (error) {
|
|
354
|
-
genLogger.warn(`Failed to parse route file: ${filePath}`, error);
|
|
355
401
|
}
|
|
356
|
-
return routes;
|
|
357
402
|
}
|
|
358
|
-
function
|
|
359
|
-
|
|
360
|
-
|
|
403
|
+
function collectRenamedExports(compiler2, statement, found) {
|
|
404
|
+
if (!compiler2.isExportDeclaration(statement) || !statement.exportClause || !compiler2.isNamedExports(statement.exportClause)) {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
for (const specifier of statement.exportClause.elements) {
|
|
408
|
+
if (specifier.propertyName && !found.has(specifier.name.text)) {
|
|
409
|
+
found.set(specifier.name.text, specifier.propertyName);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
function unwrap(compiler2, expression) {
|
|
414
|
+
if (!expression) {
|
|
415
|
+
return void 0;
|
|
416
|
+
}
|
|
417
|
+
if (compiler2.isParenthesizedExpression(expression) || compiler2.isAsExpression(expression) || compiler2.isSatisfiesExpression(expression) || compiler2.isNonNullExpression(expression) || compiler2.isTypeAssertionExpression(expression)) {
|
|
418
|
+
return unwrap(compiler2, expression.expression);
|
|
419
|
+
}
|
|
420
|
+
return expression;
|
|
421
|
+
}
|
|
422
|
+
function routesLiteral(compiler2, expression, declarations, seen, factory) {
|
|
423
|
+
const node = unwrap(compiler2, expression);
|
|
424
|
+
if (!node) {
|
|
425
|
+
return void 0;
|
|
426
|
+
}
|
|
427
|
+
if (compiler2.isIdentifier(node)) {
|
|
428
|
+
if (seen.has(node.text)) {
|
|
429
|
+
return void 0;
|
|
430
|
+
}
|
|
431
|
+
seen.add(node.text);
|
|
432
|
+
return routesLiteral(compiler2, declarations.get(node.text), declarations, seen, factory);
|
|
433
|
+
}
|
|
434
|
+
if (!compiler2.isCallExpression(node)) {
|
|
435
|
+
return void 0;
|
|
436
|
+
}
|
|
437
|
+
const callee = unwrap(compiler2, node.expression);
|
|
438
|
+
if (callee && compiler2.isIdentifier(callee) && callee.text === factory) {
|
|
439
|
+
const routes = unwrap(compiler2, node.arguments[0]);
|
|
440
|
+
return routes && compiler2.isObjectLiteralExpression(routes) ? routes : void 0;
|
|
441
|
+
}
|
|
442
|
+
return callee && compiler2.isPropertyAccessExpression(callee) ? routesLiteral(compiler2, callee.expression, declarations, seen, factory) : void 0;
|
|
443
|
+
}
|
|
444
|
+
function assertLiteral(compiler2, file, literal, declarations, seen, scan) {
|
|
445
|
+
for (const property of literal.properties) {
|
|
446
|
+
if (compiler2.isSpreadAssignment(property)) {
|
|
447
|
+
assertUnconditionalSpread(compiler2, file, property.expression, scan);
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
const nested = routesLiteral(compiler2, mountedRouter(compiler2, property), declarations, seen, factoryOf(scan));
|
|
451
|
+
if (nested) {
|
|
452
|
+
assertLiteral(compiler2, file, nested, declarations, seen, scan);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
function mountedRouter(compiler2, property) {
|
|
457
|
+
if (compiler2.isPropertyAssignment(property)) {
|
|
458
|
+
return property.initializer;
|
|
459
|
+
}
|
|
460
|
+
return compiler2.isShorthandPropertyAssignment(property) ? property.name : void 0;
|
|
461
|
+
}
|
|
462
|
+
function assertUnconditionalSpread(compiler2, file, expression, scan) {
|
|
463
|
+
const condition = conditionKind(compiler2, expression);
|
|
464
|
+
if (!condition) {
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const wording = REFUSAL_WORDING[factoryOf(scan)];
|
|
468
|
+
throw new ConditionalRegistrationError(
|
|
469
|
+
`${scan.routerPath} registers ${wording.noun} conditionally: "...${spreadText(file, expression)}" (${condition}).
|
|
470
|
+
|
|
471
|
+
The ${scan.subject} is generated from the router as it loads, so a set of ${wording.noun} that depends on a flag or an environment describes whichever way the generator happened to run: ${wording.consequence}.
|
|
472
|
+
` + wording.remedy
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
function conditionKind(compiler2, expression) {
|
|
476
|
+
const node = unwrap(compiler2, expression);
|
|
477
|
+
if (!node) {
|
|
478
|
+
return void 0;
|
|
479
|
+
}
|
|
480
|
+
if (compiler2.isConditionalExpression(node)) {
|
|
481
|
+
return "a ternary";
|
|
482
|
+
}
|
|
483
|
+
if (!compiler2.isBinaryExpression(node)) {
|
|
484
|
+
return void 0;
|
|
485
|
+
}
|
|
486
|
+
switch (node.operatorToken.kind) {
|
|
487
|
+
case compiler2.SyntaxKind.AmpersandAmpersandToken:
|
|
488
|
+
return "&&";
|
|
489
|
+
case compiler2.SyntaxKind.BarBarToken:
|
|
490
|
+
return "||";
|
|
491
|
+
case compiler2.SyntaxKind.QuestionQuestionToken:
|
|
492
|
+
return "??";
|
|
493
|
+
default:
|
|
494
|
+
return void 0;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function spreadText(file, expression) {
|
|
498
|
+
return expression.getText(file).replace(/\s+/g, " ");
|
|
499
|
+
}
|
|
500
|
+
var loadLogger = logger.child("@spfn/core:codegen");
|
|
501
|
+
function pinNodeEnv() {
|
|
502
|
+
if (process.env.NODE_ENV) {
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
process.env.NODE_ENV = "production";
|
|
506
|
+
loadLogger.info('NODE_ENV was unset; pinned to "production" so generated output does not depend on the shell');
|
|
507
|
+
}
|
|
508
|
+
function parseHost(compiler2) {
|
|
509
|
+
return {
|
|
510
|
+
useCaseSensitiveFileNames: compiler2.sys.useCaseSensitiveFileNames,
|
|
511
|
+
readDirectory: () => [],
|
|
512
|
+
fileExists: compiler2.sys.fileExists,
|
|
513
|
+
readFile: compiler2.sys.readFile
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
var NO_INPUTS = 18003;
|
|
517
|
+
function targetPath(target, base) {
|
|
518
|
+
return resolve(base, target.endsWith("/*") ? target.slice(0, -2) : target);
|
|
519
|
+
}
|
|
520
|
+
var UNREADABLE_CODES = /* @__PURE__ */ new Set(["EACCES", "EPERM"]);
|
|
521
|
+
function isUnreadable(error) {
|
|
522
|
+
return UNREADABLE_CODES.has(error?.code ?? "");
|
|
523
|
+
}
|
|
524
|
+
function targetResolves(target, base) {
|
|
525
|
+
const path = targetPath(target, base);
|
|
526
|
+
if (!target.endsWith("/*")) {
|
|
527
|
+
return existsSync(path);
|
|
528
|
+
}
|
|
361
529
|
try {
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (importPath.startsWith(".")) {
|
|
368
|
-
importPaths.push(importPath);
|
|
369
|
-
}
|
|
530
|
+
const stats = statSync(path, { throwIfNoEntry: false });
|
|
531
|
+
return stats?.isDirectory() === true && readdirSync(path).length > 0;
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (!isUnreadable(error)) {
|
|
534
|
+
throw error;
|
|
370
535
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
536
|
+
return false;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
function chooseTarget(pattern, targets, base) {
|
|
540
|
+
const present = targets.filter((target2) => targetResolves(target2, base));
|
|
541
|
+
const [target] = present.length > 0 ? present : targets;
|
|
542
|
+
if (!target) {
|
|
543
|
+
return void 0;
|
|
544
|
+
}
|
|
545
|
+
if (present.length > 1) {
|
|
546
|
+
loadLogger.warn(
|
|
547
|
+
`tsconfig "paths" maps ${pattern} to ${present.length} targets that could each resolve a module; while the router loads, only the first (${target}) does`
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
if (present.length === 0 && targets.length > 1) {
|
|
551
|
+
loadLogger.warn(
|
|
552
|
+
`tsconfig "paths" maps ${pattern} to ${targets.length} targets and none of them exists with anything in it; ${target} is used, and an import through it will name itself as unresolved`
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
return { target, others: targets.filter((candidate) => candidate !== target) };
|
|
556
|
+
}
|
|
557
|
+
function toAlias(pattern, targets, base) {
|
|
558
|
+
const choice = chooseTarget(pattern, targets, base);
|
|
559
|
+
if (!choice) {
|
|
560
|
+
return void 0;
|
|
561
|
+
}
|
|
562
|
+
const { target, others } = choice;
|
|
563
|
+
if (!pattern.includes("*")) {
|
|
564
|
+
return { from: pattern, to: resolve(base, target), pattern, target, others };
|
|
565
|
+
}
|
|
566
|
+
if (!pattern.endsWith("/*") || !target.endsWith("/*")) {
|
|
567
|
+
loadLogger.warn(
|
|
568
|
+
`tsconfig "paths" maps ${pattern} to ${target}, which is not a directory prefix mapping; it will not resolve while the router loads`
|
|
569
|
+
);
|
|
570
|
+
return void 0;
|
|
571
|
+
}
|
|
572
|
+
return { from: pattern.slice(0, -1), to: resolve(base, target.slice(0, -2)), pattern, target, others };
|
|
573
|
+
}
|
|
574
|
+
function readCompilerOptions(configPath, cwd) {
|
|
575
|
+
if (!existsSync(configPath)) {
|
|
576
|
+
return void 0;
|
|
577
|
+
}
|
|
578
|
+
const compiler2 = typescript();
|
|
579
|
+
const { config, error } = compiler2.readConfigFile(configPath, compiler2.sys.readFile);
|
|
580
|
+
if (error || !config) {
|
|
581
|
+
loadLogger.warn(`Could not read ${relative(cwd, configPath)}; its path aliases will not resolve`);
|
|
582
|
+
return void 0;
|
|
583
|
+
}
|
|
584
|
+
const parsed = compiler2.parseJsonConfigFileContent(config, parseHost(compiler2), dirname(configPath));
|
|
585
|
+
for (const diagnostic of parsed.errors) {
|
|
586
|
+
if (diagnostic.code !== NO_INPUTS) {
|
|
587
|
+
loadLogger.warn(
|
|
588
|
+
`${relative(cwd, configPath)}: ${compiler2.flattenDiagnosticMessageText(diagnostic.messageText, " ")} \u2014 path aliases it should have declared may be missing while the router loads`
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return parsed.options;
|
|
593
|
+
}
|
|
594
|
+
function isWithin(root, directory) {
|
|
595
|
+
const step = relative(root, directory);
|
|
596
|
+
return step === "" || !step.startsWith("..") && !isAbsolute(step);
|
|
597
|
+
}
|
|
598
|
+
function searchDirectories(cwd, startDir) {
|
|
599
|
+
const root = resolve(cwd);
|
|
600
|
+
const directories = [];
|
|
601
|
+
for (let directory = resolve(startDir); isWithin(root, directory); directory = dirname(directory)) {
|
|
602
|
+
directories.push(directory);
|
|
603
|
+
if (directory === root) {
|
|
604
|
+
return directories;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return [root];
|
|
608
|
+
}
|
|
609
|
+
function aliasesOf(paths, base) {
|
|
610
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
611
|
+
for (const [pattern, targets] of Object.entries(paths)) {
|
|
612
|
+
const alias = toAlias(pattern, targets, base);
|
|
613
|
+
if (alias && !aliases.has(alias.from)) {
|
|
614
|
+
aliases.set(alias.from, alias);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return [...aliases.values()];
|
|
618
|
+
}
|
|
619
|
+
function projectAliases(cwd, startDir) {
|
|
620
|
+
for (const directory of searchDirectories(cwd, startDir)) {
|
|
621
|
+
const options = readCompilerOptions(join(directory, "tsconfig.json"), cwd);
|
|
622
|
+
if (options?.paths) {
|
|
623
|
+
const declaredIn = options.pathsBasePath;
|
|
624
|
+
return aliasesOf(options.paths, options.baseUrl ?? declaredIn ?? directory);
|
|
389
625
|
}
|
|
626
|
+
}
|
|
627
|
+
return [];
|
|
628
|
+
}
|
|
629
|
+
function describeFailure(error, subject, aliases) {
|
|
630
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
631
|
+
const unresolved = /Cannot find module '([^']+)'/.exec(message);
|
|
632
|
+
if (!unresolved) {
|
|
633
|
+
return `${message}
|
|
634
|
+
|
|
635
|
+
The ${subject} is read from the loaded router, so a route module must be importable without side effects. Check that nothing at module scope opens a connection or reads a missing environment value.`;
|
|
636
|
+
}
|
|
637
|
+
return `${message.split("\n")[0]}
|
|
638
|
+
|
|
639
|
+
"${unresolved[1]}" did not resolve while the router was being imported. Imports resolve through Node and through the "paths" of the nearest tsconfig.json that declares them, searching from the router file up to the project root. Check that the specifier is mapped in one of those, and that what it points at exists: a workspace package resolves to a dist/ that has to have been built.` + describePassedOverTargets(unresolved[1], aliases);
|
|
640
|
+
}
|
|
641
|
+
function describePassedOverTargets(specifier, aliases) {
|
|
642
|
+
const alias = aliases.find((entry) => specifier.startsWith(entry.from) || specifier.startsWith(entry.to));
|
|
643
|
+
if (!alias || alias.others.length === 0) {
|
|
644
|
+
return "";
|
|
645
|
+
}
|
|
646
|
+
return `
|
|
647
|
+
|
|
648
|
+
It was resolved through "${alias.target}", the first target of the "paths" entry "${alias.pattern}" that names a directory holding anything. That entry also lists ${alias.others.map((other) => `"${other}"`).join(", ")}, which the router load never tried: one alias per key is all the loader can express, so the whole load goes through a single target.`;
|
|
649
|
+
}
|
|
650
|
+
function loadRouterModule(load) {
|
|
651
|
+
const { cwd, absoluteRouterPath, subject, fail } = load;
|
|
652
|
+
const aliases = projectAliases(cwd, dirname(absoluteRouterPath));
|
|
653
|
+
const jiti = createJiti(cwd, {
|
|
654
|
+
interopDefault: true,
|
|
655
|
+
moduleCache: false,
|
|
656
|
+
alias: Object.fromEntries(aliases.map((alias) => [alias.from, alias.to]))
|
|
657
|
+
});
|
|
658
|
+
try {
|
|
659
|
+
return jiti(absoluteRouterPath);
|
|
390
660
|
} catch (error) {
|
|
391
|
-
|
|
661
|
+
throw fail(
|
|
662
|
+
`Failed to load ${relative(cwd, absoluteRouterPath)}: ${describeFailure(error, subject, aliases)}`
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function isRouter(value) {
|
|
667
|
+
return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
|
|
668
|
+
}
|
|
669
|
+
function resolveRouterExport(module, candidates) {
|
|
670
|
+
for (const exportName of candidates) {
|
|
671
|
+
const candidate = module[exportName];
|
|
672
|
+
if (isRouter(candidate)) {
|
|
673
|
+
return { router: candidate, exportName };
|
|
674
|
+
}
|
|
392
675
|
}
|
|
393
|
-
return
|
|
676
|
+
return void 0;
|
|
394
677
|
}
|
|
395
|
-
|
|
678
|
+
|
|
679
|
+
// src/codegen/generators/route-map.ts
|
|
680
|
+
var genLogger = logger.child("@spfn/core:route-map-generator");
|
|
681
|
+
var RouteMapGeneratorError = class extends Error {
|
|
682
|
+
constructor(message) {
|
|
683
|
+
super(message);
|
|
684
|
+
this.name = "RouteMapGeneratorError";
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
function isRouteDef(value) {
|
|
688
|
+
return value !== null && typeof value === "object" && "handler" in value;
|
|
689
|
+
}
|
|
690
|
+
var ROUTER_EXPORTS = ["appRouter", "default", "router"];
|
|
691
|
+
function loadRouter(cwd, absoluteRouterPath) {
|
|
692
|
+
const module = loadRouterModule({
|
|
693
|
+
cwd,
|
|
694
|
+
absoluteRouterPath,
|
|
695
|
+
subject: "route map",
|
|
696
|
+
fail: (message) => new RouteMapGeneratorError(message)
|
|
697
|
+
});
|
|
698
|
+
const resolved = resolveRouterExport(module, ROUTER_EXPORTS);
|
|
699
|
+
if (resolved) {
|
|
700
|
+
return resolved;
|
|
701
|
+
}
|
|
702
|
+
throw new RouteMapGeneratorError(
|
|
703
|
+
`No router found in ${relative(cwd, absoluteRouterPath)}. Looked for: ${ROUTER_EXPORTS.join(", ")}. Export the defineRouter() result under one of those names.`
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
var HTTP_METHODS = { GET: true, POST: true, PUT: true, PATCH: true, DELETE: true };
|
|
707
|
+
function duplicateNameError(origin, name, existing, where) {
|
|
708
|
+
if (origin === "app") {
|
|
709
|
+
return new RouteMapGeneratorError(
|
|
710
|
+
`Two routes are both named "${name}" (${existing.trail} and ${where}). The RPC client addresses a route by its name alone, and a nested route registers under its own key, so a name must be unique across the whole router.`
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
return new RouteMapGeneratorError(
|
|
714
|
+
`Two package routers both register a route named "${name}" (${existing.trail} and ${where}). Both are written into this app's route map, which holds one entry per name, so one of the two packages would have its client call the other package's path. Nothing of this app's can be renamed to fix it: drop one of the two mounts, or raise the name with the package that took it second.`
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
function addRoute(name, routeDef, trail, into, origin) {
|
|
718
|
+
const where = trail.join(".");
|
|
719
|
+
if (!routeDef.method || !routeDef.path) {
|
|
720
|
+
genLogger.warn(
|
|
721
|
+
`Route "${where}" has no method or path and is left out of the map. The RPC client resolves a name to a method and a path, so both are required. A route reaches this state by being registered before .handler() was called \u2014 the server skips it too.`
|
|
722
|
+
);
|
|
723
|
+
return void 0;
|
|
724
|
+
}
|
|
725
|
+
if (!Object.hasOwn(HTTP_METHODS, routeDef.method)) {
|
|
726
|
+
throw new RouteMapGeneratorError(
|
|
727
|
+
`Route "${where}" declares the method "${routeDef.method}", which is not an HttpMethod (${Object.keys(HTTP_METHODS).join(", ")}). The generated map is typed HttpMethod, so naming it would write a file that does not compile.`
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
const existing = into.get(name);
|
|
731
|
+
if (existing) {
|
|
732
|
+
if (origin === "package" && existing.def === routeDef) {
|
|
733
|
+
return void 0;
|
|
734
|
+
}
|
|
735
|
+
throw duplicateNameError(origin, name, existing, where);
|
|
736
|
+
}
|
|
737
|
+
const collected = {
|
|
738
|
+
method: routeDef.method,
|
|
739
|
+
path: routeDef.path,
|
|
740
|
+
trail: where,
|
|
741
|
+
def: routeDef
|
|
742
|
+
};
|
|
743
|
+
into.set(name, collected);
|
|
744
|
+
return collected;
|
|
745
|
+
}
|
|
746
|
+
function pathPrefix(path) {
|
|
747
|
+
const [, first] = path.split("/");
|
|
748
|
+
return first ? `/${first}` : path;
|
|
749
|
+
}
|
|
750
|
+
function collectPackageRoutes(router, trail, mount, collection) {
|
|
751
|
+
if (router._publishesRouteMap === false || collection.visited.has(router)) {
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
collection.visited.set(router, trail.join("."));
|
|
755
|
+
for (const [name, entry] of Object.entries(router.routes)) {
|
|
756
|
+
if (isRouter(entry)) {
|
|
757
|
+
collectPackageRoutes(entry, [...trail, name], mount, collection);
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
if (!isRouteDef(entry)) {
|
|
761
|
+
genLogger.warn(
|
|
762
|
+
`Package router entry "${[...trail, name].join(".")}" is neither a route nor a router (got ${typeof entry}) and is left out of the map. \`registerRoutes\` skips it too.`
|
|
763
|
+
);
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
const collected = addRoute(name, entry, [...trail, name], collection.packages, "package");
|
|
767
|
+
if (collected) {
|
|
768
|
+
mount.count += 1;
|
|
769
|
+
mount.prefixes.add(pathPrefix(collected.path));
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
const already = collection.packages.get(name);
|
|
773
|
+
if (already?.def === entry) {
|
|
774
|
+
mount.sharedWith ??= already.trail;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
for (const [index, nested] of (router._packageRouters ?? []).entries()) {
|
|
778
|
+
collectPackageRoutes(nested, [...trail, `packages[${index}]`], mount, collection);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function mountPackageRouter(router, label, collection) {
|
|
782
|
+
const mount = { label, count: 0, prefixes: /* @__PURE__ */ new Set() };
|
|
783
|
+
const alreadyAt = collection.visited.get(router);
|
|
784
|
+
if (router._publishesRouteMap === false) {
|
|
785
|
+
mount.skipped = "publishes no route map";
|
|
786
|
+
} else if (alreadyAt) {
|
|
787
|
+
mount.skipped = `already reached through ${alreadyAt}`;
|
|
788
|
+
}
|
|
789
|
+
collectPackageRoutes(router, [label], mount, collection);
|
|
790
|
+
if (mount.count === 0 && !mount.skipped && mount.sharedWith) {
|
|
791
|
+
mount.skipped = `every route it holds was already collected through ${mount.sharedWith}`;
|
|
792
|
+
}
|
|
793
|
+
collection.mounts.push(mount);
|
|
794
|
+
return mount;
|
|
795
|
+
}
|
|
796
|
+
function collectRoutes(router, trail, collection) {
|
|
797
|
+
for (const [name, entry] of Object.entries(router.routes)) {
|
|
798
|
+
if (isRouter(entry)) {
|
|
799
|
+
collectRoutes(entry, [...trail, name], collection);
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
if (!isRouteDef(entry)) {
|
|
803
|
+
genLogger.warn(
|
|
804
|
+
`Router entry "${[...trail, name].join(".")}" is neither a route nor a router (got ${typeof entry}) and is left out of the map. \`registerRoutes\` skips it too, so no name the client can call goes unanswered.`
|
|
805
|
+
);
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
addRoute(name, entry, [...trail, name], collection.app, "app");
|
|
809
|
+
}
|
|
810
|
+
for (const [index, packageRouter] of (router._packageRouters ?? []).entries()) {
|
|
811
|
+
mountPackageRouter(packageRouter, `${trail.join(".")}.packages[${index}]`, collection);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
function assertNoPackageCollision(collection) {
|
|
815
|
+
for (const [name, route] of collection.packages) {
|
|
816
|
+
const appRoute = collection.app.get(name);
|
|
817
|
+
if (!appRoute) {
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
throw new RouteMapGeneratorError(
|
|
821
|
+
`The app route "${name}" (${appRoute.trail}) is also registered by a package router (${route.trail}). Both go into this app's generated route map, which holds one entry per name, so one of the two paths becomes unreachable while the typed client still describes the app's route. Rename the app route.`
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
function collectRouteMap(router) {
|
|
826
|
+
const collection = {
|
|
827
|
+
app: /* @__PURE__ */ new Map(),
|
|
828
|
+
packages: /* @__PURE__ */ new Map(),
|
|
829
|
+
mounts: [],
|
|
830
|
+
visited: /* @__PURE__ */ new Map()
|
|
831
|
+
};
|
|
832
|
+
collectRoutes(router, ["router"], collection);
|
|
833
|
+
assertNoPackageCollision(collection);
|
|
834
|
+
return collection;
|
|
835
|
+
}
|
|
836
|
+
function toObjectKey(name) {
|
|
837
|
+
if (name === "__proto__") {
|
|
838
|
+
return `[${JSON.stringify(name)}]`;
|
|
839
|
+
}
|
|
840
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
|
|
841
|
+
}
|
|
842
|
+
var SINGLE_QUOTABLE = /^[\x20-\x26\x28-\x5B\x5D-\x7E]*$/;
|
|
843
|
+
function toStringLiteral(value) {
|
|
844
|
+
if (SINGLE_QUOTABLE.test(value)) {
|
|
845
|
+
return `'${value}'`;
|
|
846
|
+
}
|
|
847
|
+
return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
848
|
+
}
|
|
849
|
+
function describeMount(mount) {
|
|
850
|
+
if (mount.count === 0) {
|
|
851
|
+
return `${mount.label} \u2014 no routes${mount.skipped ? ` (${mount.skipped})` : ""}`;
|
|
852
|
+
}
|
|
853
|
+
const routes = `${mount.count} route${mount.count === 1 ? "" : "s"}`;
|
|
854
|
+
return `${mount.label} \u2014 ${routes} under ${[...mount.prefixes].join(", ")}`;
|
|
855
|
+
}
|
|
856
|
+
function packageHeaderLines(collection) {
|
|
857
|
+
if (collection.packages.size === 0) {
|
|
858
|
+
return [];
|
|
859
|
+
}
|
|
860
|
+
return [
|
|
861
|
+
" *",
|
|
862
|
+
" * The entries under the .packages() line below are not this app's. They belong",
|
|
863
|
+
" * to the package routers it mounts, copied in as they were when this file was",
|
|
864
|
+
" * generated:",
|
|
865
|
+
...collection.mounts.map((mount) => ` * ${describeMount(mount)}`),
|
|
866
|
+
" *",
|
|
867
|
+
" * A package upgrade reaches them only through a regeneration: `spfn build`",
|
|
868
|
+
" * regenerates before it compiles, a bare `next build` uses what is committed here."
|
|
869
|
+
];
|
|
870
|
+
}
|
|
871
|
+
function generateRouteMapContent(collection, nodeEnv) {
|
|
396
872
|
const lines = [
|
|
397
873
|
"/**",
|
|
398
874
|
" * Route Map (Auto-generated)",
|
|
399
875
|
" *",
|
|
400
876
|
" * DO NOT EDIT - This file is generated by @spfn/core:route-map generator",
|
|
877
|
+
" *",
|
|
878
|
+
` * Generated with NODE_ENV=${nodeEnv}. A route registered only under one environment is`,
|
|
879
|
+
" * named here only when the generator ran under it, so this line changing is that",
|
|
880
|
+
" * difference rather than an edit.",
|
|
881
|
+
...packageHeaderLines(collection),
|
|
401
882
|
" */",
|
|
402
883
|
"",
|
|
403
884
|
"import type { HttpMethod } from '@spfn/core/route';",
|
|
@@ -410,8 +891,14 @@ function generateRouteMapContent(routes) {
|
|
|
410
891
|
"",
|
|
411
892
|
"export const routeMap: Record<string, RouteInfo> = {"
|
|
412
893
|
];
|
|
413
|
-
for (const route of
|
|
414
|
-
lines.push(
|
|
894
|
+
for (const [name, route] of collection.app) {
|
|
895
|
+
lines.push(entryLine(name, route));
|
|
896
|
+
}
|
|
897
|
+
if (collection.packages.size > 0) {
|
|
898
|
+
lines.push(" // From the package routers this app mounts with .packages(), not its own:");
|
|
899
|
+
for (const [name, route] of collection.packages) {
|
|
900
|
+
lines.push(entryLine(name, route));
|
|
901
|
+
}
|
|
415
902
|
}
|
|
416
903
|
lines.push("};");
|
|
417
904
|
lines.push("");
|
|
@@ -421,6 +908,9 @@ function generateRouteMapContent(routes) {
|
|
|
421
908
|
lines.push("");
|
|
422
909
|
return lines.join("\n");
|
|
423
910
|
}
|
|
911
|
+
function entryLine(name, route) {
|
|
912
|
+
return ` ${toObjectKey(name)}: { method: '${route.method}', path: ${toStringLiteral(route.path)} },`;
|
|
913
|
+
}
|
|
424
914
|
function createRouteMapGenerator(config) {
|
|
425
915
|
const {
|
|
426
916
|
routerPath,
|
|
@@ -440,9 +930,11 @@ Usage:
|
|
|
440
930
|
}
|
|
441
931
|
return {
|
|
442
932
|
name: "@spfn/core:route-map",
|
|
933
|
+
// Unchanged, including the deprecated dirs: what the map is *built* from
|
|
934
|
+
// moved to the loaded router, but what a rebuild should be *triggered* by
|
|
935
|
+
// is still every file a route can live in.
|
|
443
936
|
watchPatterns: [
|
|
444
937
|
routerPath,
|
|
445
|
-
// Watch route directories derived from router imports
|
|
446
938
|
"src/server/routes/**/*.ts",
|
|
447
939
|
...additionalRouteDirs.map((dir) => `${dir}/**/*.ts`)
|
|
448
940
|
],
|
|
@@ -456,97 +948,36 @@ Usage:
|
|
|
456
948
|
return;
|
|
457
949
|
}
|
|
458
950
|
if (debug) {
|
|
459
|
-
genLogger.info("
|
|
460
|
-
}
|
|
461
|
-
const { importPaths, routeNames } = parseRouterFile(absoluteRouterPath);
|
|
462
|
-
if (debug) {
|
|
463
|
-
genLogger.info("Found route imports", { count: importPaths.length, names: routeNames });
|
|
464
|
-
}
|
|
465
|
-
const routerDir = dirname(absoluteRouterPath);
|
|
466
|
-
const allRoutes = [];
|
|
467
|
-
for (const importPath of importPaths) {
|
|
468
|
-
let resolvedPath = resolve(routerDir, importPath);
|
|
469
|
-
if (!resolvedPath.endsWith(".ts")) {
|
|
470
|
-
const withTs = resolvedPath + ".ts";
|
|
471
|
-
if (existsSync(withTs)) {
|
|
472
|
-
resolvedPath = withTs;
|
|
473
|
-
} else {
|
|
474
|
-
const indexPath = join(resolvedPath, "index.ts");
|
|
475
|
-
if (existsSync(indexPath)) {
|
|
476
|
-
resolvedPath = indexPath;
|
|
477
|
-
} else {
|
|
478
|
-
resolvedPath = withTs;
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
if (existsSync(resolvedPath)) {
|
|
483
|
-
const routes = parseRouteFile(resolvedPath);
|
|
484
|
-
allRoutes.push(...routes);
|
|
485
|
-
if (debug) {
|
|
486
|
-
genLogger.info(`Parsed ${routes.length} routes from ${relative(cwd, resolvedPath)}`);
|
|
487
|
-
}
|
|
488
|
-
}
|
|
951
|
+
genLogger.info("Loading router", { path: absoluteRouterPath });
|
|
489
952
|
}
|
|
490
|
-
|
|
953
|
+
pinNodeEnv();
|
|
954
|
+
const { router, exportName } = loadRouter(cwd, absoluteRouterPath);
|
|
955
|
+
assertUnconditionalRegistration({
|
|
956
|
+
routerPath,
|
|
957
|
+
source: readFileSync(absoluteRouterPath, "utf-8"),
|
|
958
|
+
exportName,
|
|
959
|
+
subject: "route map"
|
|
960
|
+
});
|
|
961
|
+
const collection = collectRouteMap(router);
|
|
962
|
+
const total = collection.app.size + collection.packages.size;
|
|
491
963
|
if (debug) {
|
|
492
|
-
genLogger.info(`Found ${
|
|
964
|
+
genLogger.info(`Found ${total} routes`, {
|
|
965
|
+
app: [...collection.app.keys()],
|
|
966
|
+
packages: [...collection.packages.keys()]
|
|
967
|
+
});
|
|
493
968
|
}
|
|
494
|
-
const content = generateRouteMapContent(exportedRoutes);
|
|
495
969
|
const outputDir = dirname(absoluteOutputPath);
|
|
496
970
|
if (!existsSync(outputDir)) {
|
|
497
971
|
mkdirSync(outputDir, { recursive: true });
|
|
498
972
|
}
|
|
499
|
-
|
|
500
|
-
|
|
973
|
+
const nodeEnv = process.env.NODE_ENV ?? "unset";
|
|
974
|
+
writeFileSync(absoluteOutputPath, generateRouteMapContent(collection, nodeEnv), "utf-8");
|
|
975
|
+
genLogger.info(
|
|
976
|
+
`Generated route map: ${relative(cwd, absoluteOutputPath)} (${collection.app.size} app routes, ${collection.packages.size} from mounted packages)`
|
|
977
|
+
);
|
|
501
978
|
}
|
|
502
979
|
};
|
|
503
980
|
}
|
|
504
|
-
|
|
505
|
-
// src/codegen/generators/contract-guard.ts
|
|
506
|
-
var ConditionalRegistrationError = class extends Error {
|
|
507
|
-
constructor(message) {
|
|
508
|
-
super(message);
|
|
509
|
-
this.name = "ConditionalRegistrationError";
|
|
510
|
-
}
|
|
511
|
-
};
|
|
512
|
-
function defineRouterBlock(source) {
|
|
513
|
-
const start = source.indexOf("defineRouter(");
|
|
514
|
-
if (start === -1) {
|
|
515
|
-
return void 0;
|
|
516
|
-
}
|
|
517
|
-
const open = source.indexOf("{", start);
|
|
518
|
-
if (open === -1) {
|
|
519
|
-
return void 0;
|
|
520
|
-
}
|
|
521
|
-
let depth = 1;
|
|
522
|
-
let cursor = open + 1;
|
|
523
|
-
while (depth > 0 && cursor < source.length) {
|
|
524
|
-
if (source[cursor] === "{") depth++;
|
|
525
|
-
else if (source[cursor] === "}") depth--;
|
|
526
|
-
cursor++;
|
|
527
|
-
}
|
|
528
|
-
return source.slice(open + 1, cursor - 1).replace(/\/\/[^\n]*/g, "");
|
|
529
|
-
}
|
|
530
|
-
var PLAIN_REFERENCE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*\s*$/;
|
|
531
|
-
function assertUnconditionalRegistration(routerPath, source) {
|
|
532
|
-
const block = defineRouterBlock(source);
|
|
533
|
-
if (!block) {
|
|
534
|
-
return;
|
|
535
|
-
}
|
|
536
|
-
for (const [, expression] of block.matchAll(/\.\.\.\s*([^,\n]+)/g)) {
|
|
537
|
-
if (PLAIN_REFERENCE.test(expression)) {
|
|
538
|
-
continue;
|
|
539
|
-
}
|
|
540
|
-
throw new ConditionalRegistrationError(
|
|
541
|
-
`${routerPath} registers routes conditionally: "...${expression.trim()}".
|
|
542
|
-
|
|
543
|
-
A contract has to describe what production serves. When the route set depends on a flag or an environment, the generated contract describes whichever way the generator happened to run.
|
|
544
|
-
Register contracted routes unconditionally, and gate behaviour inside the handler instead.`
|
|
545
|
-
);
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// src/codegen/generators/contract.ts
|
|
550
981
|
var genLogger2 = logger.child("@spfn/core:contract-generator");
|
|
551
982
|
var ContractGeneratorError = class extends Error {
|
|
552
983
|
constructor(message) {
|
|
@@ -554,43 +985,67 @@ var ContractGeneratorError = class extends Error {
|
|
|
554
985
|
this.name = "ContractGeneratorError";
|
|
555
986
|
}
|
|
556
987
|
};
|
|
557
|
-
function
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
module = jiti(absoluteRouterPath);
|
|
565
|
-
} catch (error) {
|
|
566
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
567
|
-
throw new ContractGeneratorError(
|
|
568
|
-
`Failed to load ${relative(cwd, absoluteRouterPath)}: ${message}
|
|
569
|
-
|
|
570
|
-
The contract is read from the loaded router, so a route module must be importable without side effects. Check that nothing at module scope opens a connection or reads a missing environment value.`
|
|
571
|
-
);
|
|
572
|
-
}
|
|
988
|
+
function loadRouter2(cwd, absoluteRouterPath, routerExport) {
|
|
989
|
+
const module = loadRouterModule({
|
|
990
|
+
cwd,
|
|
991
|
+
absoluteRouterPath,
|
|
992
|
+
subject: "contract",
|
|
993
|
+
fail: (message) => new ContractGeneratorError(message)
|
|
994
|
+
});
|
|
573
995
|
const candidates = routerExport ? [routerExport] : ["appRouter", "default", "router"];
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
return candidate;
|
|
578
|
-
}
|
|
996
|
+
const resolved = resolveRouterExport(module, candidates);
|
|
997
|
+
if (resolved) {
|
|
998
|
+
return resolved;
|
|
579
999
|
}
|
|
580
1000
|
throw new ContractGeneratorError(
|
|
581
1001
|
`No router found in ${relative(cwd, absoluteRouterPath)}. Looked for: ${candidates.join(", ")}. Set "routerExport" to the export holding the defineRouter() result.`
|
|
582
1002
|
);
|
|
583
1003
|
}
|
|
584
|
-
function
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
1004
|
+
function isEventRouter(value) {
|
|
1005
|
+
return value !== null && typeof value === "object" && "events" in value && "eventNames" in value;
|
|
1006
|
+
}
|
|
1007
|
+
function loadEventRouter(cwd, absolutePath, eventRouterExport) {
|
|
1008
|
+
const module = loadRouterModule({
|
|
1009
|
+
cwd,
|
|
1010
|
+
absoluteRouterPath: absolutePath,
|
|
1011
|
+
subject: "contract",
|
|
1012
|
+
fail: (message) => new ContractGeneratorError(message)
|
|
1013
|
+
});
|
|
1014
|
+
const candidates = eventRouterExport ? [eventRouterExport] : ["eventRouter", "default"];
|
|
1015
|
+
const exportName = candidates.find((candidate) => isEventRouter(module[candidate]));
|
|
1016
|
+
if (exportName) {
|
|
1017
|
+
return { eventRouter: module[exportName], exportName };
|
|
588
1018
|
}
|
|
1019
|
+
throw new ContractGeneratorError(
|
|
1020
|
+
`No event router found in ${relative(cwd, absolutePath)}. Looked for: ${candidates.join(", ")}. Set "eventRouterExport" to the export holding the defineEventRouter() result.`
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
function readEventRouter(cwd, eventRouterPath, eventRouterExport) {
|
|
1024
|
+
if (!eventRouterPath) {
|
|
1025
|
+
return void 0;
|
|
1026
|
+
}
|
|
1027
|
+
const absolutePath = join(cwd, eventRouterPath);
|
|
1028
|
+
if (!existsSync(absolutePath)) {
|
|
1029
|
+
throw new ContractGeneratorError(
|
|
1030
|
+
`Event router file not found: ${eventRouterPath}. The contract generator is configured with "eventRouterPath" but has nothing to read there.`
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
const { eventRouter, exportName } = loadEventRouter(cwd, absolutePath, eventRouterExport);
|
|
1034
|
+
assertUnconditionalRegistration({
|
|
1035
|
+
routerPath: eventRouterPath,
|
|
1036
|
+
source: readFileSync(absolutePath, "utf-8"),
|
|
1037
|
+
exportName,
|
|
1038
|
+
subject: "contract",
|
|
1039
|
+
factory: "defineEventRouter"
|
|
1040
|
+
});
|
|
1041
|
+
return eventRouter;
|
|
589
1042
|
}
|
|
590
1043
|
function createContractGenerator(config) {
|
|
591
1044
|
const {
|
|
592
1045
|
routerPath,
|
|
593
1046
|
routerExport,
|
|
1047
|
+
eventRouterPath,
|
|
1048
|
+
eventRouterExport,
|
|
594
1049
|
outputDir = "./contracts",
|
|
595
1050
|
additionalRouteDirs = []
|
|
596
1051
|
} = config;
|
|
@@ -609,6 +1064,7 @@ Usage:
|
|
|
609
1064
|
name: "@spfn/core:contract",
|
|
610
1065
|
watchPatterns: [
|
|
611
1066
|
routerPath,
|
|
1067
|
+
...eventRouterPath ? [eventRouterPath] : [],
|
|
612
1068
|
"src/server/routes/**/*.ts",
|
|
613
1069
|
...additionalRouteDirs.map((dir) => `${dir}/**/*.ts`)
|
|
614
1070
|
],
|
|
@@ -623,9 +1079,14 @@ Usage:
|
|
|
623
1079
|
);
|
|
624
1080
|
}
|
|
625
1081
|
pinNodeEnv();
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
1082
|
+
const { router, exportName } = loadRouter2(cwd, absoluteRouterPath, routerExport);
|
|
1083
|
+
assertUnconditionalRegistration({
|
|
1084
|
+
routerPath,
|
|
1085
|
+
source: readFileSync(absoluteRouterPath, "utf-8"),
|
|
1086
|
+
exportName,
|
|
1087
|
+
subject: "contract"
|
|
1088
|
+
});
|
|
1089
|
+
const document = collectContractDocument(router, readEventRouter(cwd, eventRouterPath, eventRouterExport));
|
|
629
1090
|
const changed = writeCurrentDocument(contractsDir, document);
|
|
630
1091
|
genLogger2.info(
|
|
631
1092
|
`${changed ? "Wrote" : "Verified"} ${relative(cwd, join(contractsDir, "current.json"))} (${document.operations.length} contracted operation(s))`
|
|
@@ -660,6 +1121,6 @@ var generators = {
|
|
|
660
1121
|
contract: createContractGenerator
|
|
661
1122
|
};
|
|
662
1123
|
|
|
663
|
-
export { CodegenOrchestrator, ConditionalRegistrationError, ContractGeneratorError, assertUnconditionalRegistration, createGeneratorsFromConfig, defineConfig, defineGenerator, generators, loadCodegenConfig };
|
|
1124
|
+
export { CodegenOrchestrator, ConditionalRegistrationError, ContractGeneratorError, RouteMapGeneratorError, assertUnconditionalRegistration, createGeneratorsFromConfig, defineConfig, defineGenerator, generators, loadCodegenConfig };
|
|
664
1125
|
//# sourceMappingURL=index.js.map
|
|
665
1126
|
//# sourceMappingURL=index.js.map
|