Skip to content
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 80 additions & 4 deletions src/typescript-generator/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export class Script {
public repository: Repository;
public comments: string[];
public exports: Map<string, ExportStatement>;
public versions: Map<string, Map<string, ExportStatement>>;
public imports: Map<string, ImportEntry>;
public externalImport: Map<string, ExternalImportEntry>;
public cache: Map<string, string>;
Expand All @@ -49,6 +50,7 @@ export class Script {
this.repository = repository;
this.comments = [];
this.exports = new Map();
this.versions = new Map();
this.imports = new Map();
this.externalImport = new Map();
this.cache = new Map();
Expand Down Expand Up @@ -248,17 +250,69 @@ export class Script {
return this.export(coder, true);
}

public declareVersion(coder: Coder, name: string): void {
const version =
(coder as Coder & {
version?: string;
}).version ?? "";

const versions = this.versions.get(name) ?? new Map<string, ExportStatement>();
this.versions.set(name, versions);

if (versions.has(version)) {
return;
}

const versionStatement: ExportStatement = {
beforeExport: "",
done: false,
id: coder.id,
isDefault: false,
isType: true,
jsdoc: "",
typeDeclaration: coder.typeDeclaration(this.exports, this),
};

versionStatement.promise = coder
.delegate()
.then((availableCoder) => {
versionStatement.code = availableCoder.write(this);

return availableCoder;
})
.catch((error: Error) => {
versionStatement.code = `{/* error declaring version "${name}" (${version}) for ${this.path}: ${error.stack} */}`;
versionStatement.error = error;
return undefined;
})
.finally(() => {
versionStatement.done = true;
});

versions.set(version, versionStatement);
}

/** `true` while at least one export promise is still pending. */
public isInProgress(): boolean {
return Array.from(this.exports.values()).some(
(exportStatement) => !exportStatement.done,
return (
Array.from(this.exports.values()).some(
(exportStatement) => !exportStatement.done,
) ||
Array.from(this.versions.values())
.flatMap((versions) => Array.from(versions.values()))
.some((versionStatement) => !versionStatement.done)
);
}

/** Returns a promise that resolves when all pending export promises settle. */
public finished(): Promise<(Coder | undefined)[]> {
return Promise.all(
Array.from(this.exports.values(), (value) => value.promise!),
[
...Array.from(this.exports.values(), (value) => value.promise!),
...Array.from(this.versions.values())
.flatMap((versions) => Array.from(versions.values()))
.map((value) => value.promise!),
],
);
}

Expand Down Expand Up @@ -318,19 +372,41 @@ export class Script {
);
}

public versionsTypeStatements(): string[] {
if (this.versions.size === 0) {
return [];
}

const names = Array.from(this.versions, ([name, versions]) => {
const mappedVersions = Array.from(
versions,
([version, versionStatement]) =>
`"${version}": ${versionStatement.typeDeclaration || (versionStatement.code as string)}`,
);

return `"${name}": { ${mappedVersions.join(", ")} }`;
});

return [`export type Versions = { ${names.join(", ")} };`];
}

/**
* Formats the fully assembled script source with Prettier and returns it.
*
* All pending export promises are awaited before formatting.
*/
public contents(): Promise<string> {
public async contents(): Promise<string> {
await this.finished();

return format(
[
this.comments.map((comment) => `// ${comment}`).join("\n"),
this.comments.length > 0 ? "\n\n" : "",
this.externalImportStatements().join("\n"),
this.importStatements().join("\n"),
"\n\n",
this.versionsTypeStatements().join("\n"),
this.versions.size > 0 ? "\n\n" : "",
this.exportStatements().join("\n\n"),
].join(""),
{ parser: "typescript" },
Expand Down
58 changes: 58 additions & 0 deletions test/typescript-generator/script.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,45 @@ describe("a Script", () => {
]);
});

it("declares versioned code grouped by name and coder version", async () => {
const repository = new Repository("/base/path");

class V1AccountTypeCoder extends Coder {
public version = "1.0.0";

*names() {
yield "AccountV1";
}

write() {
return "{ id: string }";
}
}

class V2AccountTypeCoder extends Coder {
public version = "2.0.0";

*names() {
yield "AccountV2";
}

write() {
return "{ id: string, email: string }";
}
}

const script = repository.get("export-to-me.ts");

script.declareVersion(new V1AccountTypeCoder({}), "Account");
script.declareVersion(new V2AccountTypeCoder({}), "Account");

await script.finished();

expect(script.versionsTypeStatements()).toStrictEqual([
'export type Versions = { "Account": { "1.0.0": { id: string }, "2.0.0": { id: string, email: string } } };',
]);
});

it("outputs the contents (import and export statements)", async () => {
const repository = new Repository("/base/path");

Expand All @@ -246,4 +285,23 @@ describe("a Script", () => {
'// This is a comment.\n\nimport { foo } from "./foo.js";\n\nexport const bar = "Bar";\n\nexport default class {}\n',
);
});

it("outputs the contents including Versions when versions are declared", async () => {
const repository = new Repository("/base/path");
const script = repository.get("script.ts");

class UserCoder extends Coder {
public version = "2025-01";

write() {
return "{ id: string }";
}
}

script.declareVersion(new UserCoder({}), "User");

await expect(script.contents()).resolves.toContain(
'export type Versions = { User: { "2025-01": { id: string } } };\n',
);
});
});
Loading