@orthograph/projections 0.0.0-stage → 0.1.0-next.1

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.
Files changed (111) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +26 -2
  3. package/dist/main.d.ts +9 -0
  4. package/dist/main.js +12 -0
  5. package/dist/modules/actions/internal/actions.d.ts +7 -0
  6. package/dist/modules/actions/internal/actions.js +22 -0
  7. package/dist/modules/actions/service.d.ts +5 -0
  8. package/dist/modules/actions/service.js +14 -0
  9. package/dist/modules/actions/types.d.ts +9 -0
  10. package/dist/modules/actions/types.js +5 -0
  11. package/dist/modules/api/internal/api.d.ts +4 -0
  12. package/dist/modules/api/internal/api.js +99 -0
  13. package/dist/modules/api/service.d.ts +5 -0
  14. package/dist/modules/api/service.js +16 -0
  15. package/dist/modules/api/types.d.ts +1 -0
  16. package/dist/modules/api/types.js +1 -0
  17. package/dist/modules/app/internal/links.d.ts +2 -0
  18. package/dist/modules/app/internal/links.js +22 -0
  19. package/dist/modules/app/internal/palette.d.ts +6 -0
  20. package/dist/modules/app/internal/palette.js +55 -0
  21. package/dist/modules/app/internal/render.d.ts +4 -0
  22. package/dist/modules/app/internal/render.js +30 -0
  23. package/dist/modules/app/internal/view.d.ts +3 -0
  24. package/dist/modules/app/internal/view.js +52 -0
  25. package/dist/modules/app/service.d.ts +5 -0
  26. package/dist/modules/app/service.js +17 -0
  27. package/dist/modules/app/types.d.ts +52 -0
  28. package/dist/modules/app/types.js +1 -0
  29. package/dist/modules/cli/internal/cli.d.ts +3 -0
  30. package/dist/modules/cli/internal/cli.js +35 -0
  31. package/dist/modules/cli/internal/session.d.ts +11 -0
  32. package/dist/modules/cli/internal/session.js +55 -0
  33. package/dist/modules/cli/service.d.ts +2 -0
  34. package/dist/modules/cli/service.js +10 -0
  35. package/dist/modules/cli/types.d.ts +1 -0
  36. package/dist/modules/cli/types.js +1 -0
  37. package/dist/modules/handlers/internal/body.d.ts +5 -0
  38. package/dist/modules/handlers/internal/body.js +79 -0
  39. package/dist/modules/handlers/internal/calls.d.ts +17 -0
  40. package/dist/modules/handlers/internal/calls.js +80 -0
  41. package/dist/modules/handlers/internal/header.d.ts +18 -0
  42. package/dist/modules/handlers/internal/header.js +106 -0
  43. package/dist/modules/handlers/internal/paths.d.ts +18 -0
  44. package/dist/modules/handlers/internal/paths.js +11 -0
  45. package/dist/modules/handlers/internal/scaffold.d.ts +7 -0
  46. package/dist/modules/handlers/internal/scaffold.js +73 -0
  47. package/dist/modules/handlers/internal/stubs.d.ts +3 -0
  48. package/dist/modules/handlers/internal/stubs.js +120 -0
  49. package/dist/modules/handlers/internal/words.d.ts +43 -0
  50. package/dist/modules/handlers/internal/words.js +87 -0
  51. package/dist/modules/handlers/service.d.ts +5 -0
  52. package/dist/modules/handlers/service.js +9 -0
  53. package/dist/modules/handlers/types.d.ts +2 -0
  54. package/dist/modules/handlers/types.js +1 -0
  55. package/dist/modules/infra/internal/stack.d.ts +3 -0
  56. package/dist/modules/infra/internal/stack.js +15 -0
  57. package/dist/modules/infra/service.d.ts +5 -0
  58. package/dist/modules/infra/service.js +13 -0
  59. package/dist/modules/infra/types.d.ts +1 -0
  60. package/dist/modules/infra/types.js +1 -0
  61. package/dist/modules/mcp/internal/mcp.d.ts +3 -0
  62. package/dist/modules/mcp/internal/mcp.js +20 -0
  63. package/dist/modules/mcp/service.d.ts +5 -0
  64. package/dist/modules/mcp/service.js +13 -0
  65. package/dist/modules/mcp/types.d.ts +1 -0
  66. package/dist/modules/mcp/types.js +1 -0
  67. package/dist/modules/model/internal/edges.d.ts +4 -0
  68. package/dist/modules/model/internal/edges.js +12 -0
  69. package/dist/modules/model/service.d.ts +6 -0
  70. package/dist/modules/model/service.js +20 -0
  71. package/dist/modules/model/types.d.ts +1 -0
  72. package/dist/modules/model/types.js +1 -0
  73. package/dist/modules/names/internal/names.d.ts +51 -0
  74. package/dist/modules/names/internal/names.js +47 -0
  75. package/dist/modules/names/internal/when.d.ts +5 -0
  76. package/dist/modules/names/internal/when.js +19 -0
  77. package/dist/modules/names/internal/words.d.ts +34 -0
  78. package/dist/modules/names/internal/words.js +61 -0
  79. package/dist/modules/names/service.d.ts +19 -0
  80. package/dist/modules/names/service.js +19 -0
  81. package/dist/modules/names/types.d.ts +16 -0
  82. package/dist/modules/names/types.js +5 -0
  83. package/dist/modules/sdk/internal/client.d.ts +2 -0
  84. package/dist/modules/sdk/internal/client.js +31 -0
  85. package/dist/modules/sdk/internal/sdk.d.ts +3 -0
  86. package/dist/modules/sdk/internal/sdk.js +68 -0
  87. package/dist/modules/sdk/internal/types.d.ts +8 -0
  88. package/dist/modules/sdk/internal/types.js +38 -0
  89. package/dist/modules/sdk/service.d.ts +5 -0
  90. package/dist/modules/sdk/service.js +13 -0
  91. package/dist/modules/sdk/types.d.ts +1 -0
  92. package/dist/modules/sdk/types.js +1 -0
  93. package/dist/modules/server/internal/actors.d.ts +3 -0
  94. package/dist/modules/server/internal/actors.js +5 -0
  95. package/dist/modules/server/internal/doors.d.ts +10 -0
  96. package/dist/modules/server/internal/doors.js +26 -0
  97. package/dist/modules/server/internal/helpers.d.ts +13 -0
  98. package/dist/modules/server/internal/helpers.js +70 -0
  99. package/dist/modules/server/internal/server.d.ts +3 -0
  100. package/dist/modules/server/internal/server.js +65 -0
  101. package/dist/modules/server/internal/versioned.d.ts +13 -0
  102. package/dist/modules/server/internal/versioned.js +17 -0
  103. package/dist/modules/server/internal/worker-config.d.ts +16 -0
  104. package/dist/modules/server/internal/worker-config.js +90 -0
  105. package/dist/modules/server/service.d.ts +10 -0
  106. package/dist/modules/server/service.js +20 -0
  107. package/dist/modules/server/types.d.ts +1 -0
  108. package/dist/modules/server/types.js +1 -0
  109. package/dist/shared.d.ts +6 -0
  110. package/dist/shared.js +6 -0
  111. package/package.json +32 -3
@@ -0,0 +1,52 @@
1
+ const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2
+ const PARAM = /:([A-Za-z_][A-Za-z0-9_]*)/g;
3
+ const paramsOf = (path) => [...path.matchAll(PARAM)].map((m) => m[1]);
4
+ const declared = (model) => {
5
+ const app = model.app;
6
+ if (app === undefined)
7
+ return undefined;
8
+ const pages = Object.values(app.pages).sort(byName).map((p) => ({
9
+ name: p.name,
10
+ path: p.route.path,
11
+ params: paramsOf(p.route.path),
12
+ description: p.description,
13
+ ...(p.parent === undefined ? {} : { parent: p.parent }),
14
+ allowed: p.allowed,
15
+ shows: p.shows,
16
+ offers: p.offers,
17
+ components: p.components.map((c) => {
18
+ const component = app.components[c];
19
+ return { name: c, description: component?.description ?? "", shows: component?.shows ?? [], offers: component?.offers ?? [] };
20
+ }),
21
+ }));
22
+ const pathOf = (page) => app.pages[page]?.route.path ?? "";
23
+ const groups = app.nav.map((g) => ({ title: g.title, folded: g.folded, pages: g.pages.map((page) => ({ page, path: pathOf(page) })) }));
24
+ return { layout: app.layout, home: app.home, pages, groups };
25
+ };
26
+ const derived = (model, project) => {
27
+ const anyone = [{ kind: "anyone" }];
28
+ const things = Object.keys(model.things).sort();
29
+ // The home takes the name `home` unless a thing has it; then `home-page`, and so on, so no two pages share a name.
30
+ const home = [...Array(things.length + 1).keys()].map((i) => `home${"-page".repeat(i)}`).find((n) => !things.includes(n)) ?? "home";
31
+ const pages = [
32
+ { name: home, path: "/", params: [], description: `The things ${project} is made of.`, allowed: anyone, shows: [], offers: [], components: [] },
33
+ ...things.map((thing) => ({
34
+ name: thing,
35
+ path: `/things/${thing}`,
36
+ params: [],
37
+ description: model.things[thing]?.description || `The ${thing}, and what can be done to it.`,
38
+ parent: home,
39
+ allowed: anyone,
40
+ shows: [],
41
+ offers: Object.keys(model.operations).filter((o) => model.operations[o]?.thing === thing).sort(),
42
+ components: [],
43
+ })),
44
+ ].sort(byName);
45
+ return {
46
+ layout: "sidebar",
47
+ home,
48
+ pages,
49
+ groups: [{ title: "Things", folded: false, pages: things.map((t) => ({ page: t, path: `/things/${t}` })) }],
50
+ };
51
+ };
52
+ export const viewOf = (model, project) => declared(model) ?? derived(model, project);
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The app's map as data (`generated/app/`): the route table, a typed link per page, the navigation, the palette's index and the
3
+ * agent's map. From the declared map (`model.app`), or, with none, the one derived from the things and never written into the model.
4
+ */
5
+ export declare const app: import("orthograph").Projection<{}>;
@@ -0,0 +1,17 @@
1
+ import { Blueprint, Ships } from "orthograph";
2
+ import { modelOf, within } from "#modules/names/service.js";
3
+ import { renderApp } from "./internal/render.js";
4
+ import { viewOf } from "./internal/view.js";
5
+ /**
6
+ * The app's map as data (`generated/app/`): the route table, a typed link per page, the navigation, the palette's index and the
7
+ * agent's map. From the declared map (`model.app`), or, with none, the one derived from the things and never written into the model.
8
+ */
9
+ export const app = Blueprint.projection({
10
+ description: "The app's map as data: routes, navigation, the palette's index, the agent's map, and a typed link per page.",
11
+ host: [],
12
+ ships: [Ships.kept],
13
+ render: (input) => {
14
+ const model = modelOf(input);
15
+ return within(input, "app", renderApp(viewOf(model, input.name), model));
16
+ },
17
+ });
@@ -0,0 +1,52 @@
1
+ import type { AllowedModel } from "@orthograph/compiler";
2
+ export type { Projection } from "orthograph";
3
+ /** A component of a page: what it shows and offers (K36). */
4
+ export interface ViewComponent {
5
+ readonly name: string;
6
+ readonly description: string;
7
+ readonly shows: ReadonlyArray<string>;
8
+ readonly offers: ReadonlyArray<string>;
9
+ }
10
+ /** A page of the map, with its effective lists. */
11
+ export interface ViewPage {
12
+ readonly name: string;
13
+ readonly path: string;
14
+ /** The names of the route's parameters, in the order the path has them. */
15
+ readonly params: ReadonlyArray<string>;
16
+ readonly description: string;
17
+ readonly parent?: string;
18
+ readonly allowed: ReadonlyArray<AllowedModel>;
19
+ readonly shows: ReadonlyArray<string>;
20
+ readonly offers: ReadonlyArray<string>;
21
+ readonly components: ReadonlyArray<ViewComponent>;
22
+ }
23
+ export interface ViewGroup {
24
+ readonly title: string;
25
+ readonly folded: boolean;
26
+ readonly pages: ReadonlyArray<{
27
+ readonly page: string;
28
+ readonly path: string;
29
+ }>;
30
+ }
31
+ /** The map as the files are made from it: pages by name, groups in the order declared. */
32
+ export interface MapView {
33
+ readonly layout: string;
34
+ readonly home: string;
35
+ readonly pages: ReadonlyArray<ViewPage>;
36
+ readonly groups: ReadonlyArray<ViewGroup>;
37
+ }
38
+ /** One line of the palette: a page the caller may open, or an operation they may call where they are. */
39
+ export type PaletteEntry = {
40
+ readonly kind: "page";
41
+ readonly name: string;
42
+ readonly path: string;
43
+ readonly description: string;
44
+ readonly allowed: ReadonlyArray<AllowedModel>;
45
+ } | {
46
+ readonly kind: "operation";
47
+ readonly name: string;
48
+ readonly page: string;
49
+ readonly component: string | null;
50
+ readonly description: string;
51
+ readonly allowed: ReadonlyArray<AllowedModel>;
52
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { RenderedFile } from "#modules/names/types.js";
3
+ export declare const renderCli: (model: Model, name: string) => ReadonlyArray<RenderedFile>;
@@ -0,0 +1,35 @@
1
+ import { flagCode, helpOf, refAny } from "#modules/names/service.js";
2
+ import { renderSessionCommands, sessionOperations } from "./session.js";
3
+ import { GENERATED, camel, exportedAs, lines, local, opVar } from "#modules/names/service.js";
4
+ const command = (op) => {
5
+ const optional = Object.values(op.payload).some((f) => f.optional);
6
+ const flags = Object.entries(op.payload).map(([k, f]) => `${k}: ${f.optional ? `Flag.optional(${flagCode(k, f)})` : flagCode(k, f)}`);
7
+ return {
8
+ path: `generated/cli/src/${op.thing}/${op.verb}.ts`,
9
+ scaffold: false,
10
+ content: lines(GENERATED, `import { Effect, Schema } from "effect";`, `import { Command, Flag } from "effect/cli";`, `import { declaration as Declaration } from "../../../api/src/${op.thing}/${op.verb}.ts";`, `import * as Sdk from "../../../sdk/src/index.ts";`, `import * as Output from "../output.ts"; // a namespace, so a verb named like a helper (answer) cannot clash`, "", `/** ${op.description} Each flag is handed on as text${Object.values(op.payload).some(refAny) ? " (any-thing references are JSON objects)" : ""}${Object.values(op.payload).some((f) => f.json !== undefined) ? " (lists and objects are JSON)" : ""}; the declaration decodes it${optional ? "; a flag left out is not sent" : ""}. \`--json\` prints the whole answer as JSON. */`, `export const ${local(camel(op.verb))} = Command.make(`, ` "${op.verb}",`, ` { ${[...flags, `json: Flag.Boolean("json").pipe(Flag.withDefault(false))`].join(", ")} },`, ` ({ json, ...flags }) => Schema.decodeUnknownEffect(Declaration.payloadSchema)(${optional ? "Output.supplied(flags)" : "flags"}).pipe(Effect.flatMap(Sdk.${camel(op.thing)}.${camel(op.verb)}), Output.answer(json)),`, `).pipe(Command.withDescription(${JSON.stringify(helpOf(op))}));`, exportedAs(op.verb)),
11
+ };
12
+ };
13
+ const output = () => ({
14
+ path: "generated/cli/src/output.ts",
15
+ scaffold: false,
16
+ content: lines(GENERATED, `import { BigDecimal, Console, Context, Effect, Option } from "effect";`, `import { decimalText } from "orthograph/server";`, `import { Errors } from "../../sdk/src/index.ts";`, "", "/** Set by the entry, so commands never touch the process. */", `export class ExitCode extends Context.Service<ExitCode, { readonly set: (code: number) => Effect.Effect<void> }>()("cli/ExitCode") {}`, "", "/** The flags the caller gave: an optional flag left out is `None`, and is not sent at all. */", "export const supplied = (flags: Readonly<Record<string, unknown>>) =>", " Object.fromEntries(Object.entries(flags).flatMap(([k, v]) => (Option.isOption(v) ? (Option.isSome(v) ? [[k, v.value]] : []) : [[k, v]])));", "", "/** A value as it travels: a bigint as its digits, a decimal as its text (`1.50`, never an exponent). */", "const wire = (v: unknown): unknown => (typeof v === \"bigint\" ? v.toString() : BigDecimal.isBigDecimal(v) ? decimalText(v) : v);", "// A decimal is read from its holder, since JSON.stringify has already called its toJSON; every other value keeps what its own toJSON made of it.", "// An `Option.some` keeps its own shape but hands back what it holds, so a decimal inside it is read from its holder too.", "const text = (x: unknown) =>", " JSON.stringify(x, function (this: Readonly<Record<string, unknown>>, k: string, v: unknown) {", " const raw = this[k];", " return BigDecimal.isBigDecimal(raw) ? decimalText(raw) : Option.isOption(raw) && Option.isSome(raw) ? { ...(v as object), value: raw.value } : wire(v);", " });", "const exitOf = (tag: unknown): number =>", " typeof tag === \"string\" && Object.hasOwn(Errors.refusals, tag) ? Errors.refusals[tag as keyof typeof Errors.refusals].exit : tag === \"SchemaError\" ? 2 : 1;", "", "/** `AL-002 Name { a: 1, b: x }`: a refusal's code, its name, and the values of its declared fields that the server sent (it cut them for this caller). */", "const said = (tag: unknown, code: unknown, fields: Readonly<Record<string, unknown>>) => {", " // Only the project's own refusals have a code. Anything else (the CLI's own `NotSignedIn`) is told as it always was.", " if (typeof tag !== \"string\" || !Object.hasOwn(Errors.codes, tag)) return `${String(tag ?? \"Error\")}: ${text(fields)}`;", " const declared = (Errors.declared as Readonly<Record<string, { readonly fields: Readonly<Record<string, unknown>> }>>)[tag];", " const shown = Object.entries(fields).filter(([k]) => declared === undefined || Object.hasOwn(declared.fields, k)).map(([k, v]) => `${k}: ${typeof v === \"object\" && !BigDecimal.isBigDecimal(v) ? text(v) : String(wire(v))}`);", " return `${typeof code === \"string\" ? `[${code}] ` : \"\"}${tag}${shown.length > 0 ? ` { ${shown.join(\", \")} }` : \"\"}`;", "};", "", "/** A value printed plain: an `Option.some` of a decimal prints the decimal's text (`1.50`); anything else prints as it always did. */", "const plain = (v: unknown): string => (Option.isOption(v) && Option.isSome(v) && BigDecimal.isBigDecimal(v.value) ? decimalText(v.value) : String(wire(v)));", "", "/** A refusal prints its code, name and public fields to stderr and exits with its exit code. */", "export const refused = <A, E, R>(effect: Effect.Effect<A, E, R>) =>", " effect.pipe(", " Effect.catch((e: unknown) => {", " const tag = typeof e === \"object\" && e !== null ? (e as { readonly _tag?: unknown })._tag : undefined;", " const { _tag: _, code, ...fields } = (typeof e === \"object\" && e !== null ? e : {}) as Record<string, unknown>;", " const line = tag === \"SchemaError\" ? `SchemaError: ${String((e as { readonly message?: unknown }).message)}` : said(tag, code, fields);", " return Console.error(line).pipe(", " Effect.andThen(Effect.flatMap(ExitCode, (exit) => exit.set(exitOf(tag)))),", " );", " }),", " );", "", "/** A one-field answer prints its value, or with `json` the whole answer as JSON. */", "export const answer = (json: boolean) => <A extends object, E, R>(effect: Effect.Effect<A, E, R>) =>", " effect.pipe(Effect.flatMap((a) => Console.log(!json && Object.keys(a).length === 1 ? plain(Object.values(a)[0]) : text(a))), refused);"),
17
+ });
18
+ const main = (model, name) => {
19
+ const ops = Object.values(model.operations);
20
+ const things = [...new Set(ops.map((o) => o.thing))];
21
+ const env = name.toUpperCase().replace(/-/g, "_");
22
+ return {
23
+ path: "generated/cli/src/main.ts",
24
+ scaffold: false,
25
+ content: lines("#!/usr/bin/env node", GENERATED, `// \`${name} <thing> <verb> --<field> <value>\`. Talks to ${env}_URL, signed in with ${env}_TOKEN when set.`, `import { NodeRuntime, NodeServices } from "@effect/platform-node";`, `import { Effect, Layer } from "effect";`, `import { CliOutput, Command } from "effect/cli";`, `import * as Sdk from "../../sdk/src/index.ts";`, `import { ExitCode } from "./output.ts";`, ops.map((o) => `import { ${camel(o.verb)} as ${opVar(o)} } from "./${o.thing}/${o.verb}.ts";`), "", "// The release version is stamped in when the CLI is published (`ortho publish`); run from source, it says 0.0.0.", "declare const ORTHO_VERSION: string | undefined;", "", things.map((t) => {
26
+ const subs = ops.filter((o) => o.thing === t).map(opVar);
27
+ return `const ${local(camel(t))} = Command.make("${t}").pipe(Command.withSubcommands([${subs.join(", ")}]));`;
28
+ }), "", `Command.make("${name}").pipe(`, ` Command.withSubcommands([${things.map((t) => local(camel(t))).join(", ")}]),`, ` Command.run({ version: typeof ORTHO_VERSION === "string" ? ORTHO_VERSION : "0.0.0" }),`, " Effect.provide(CliOutput.layer({ ...CliOutput.defaultFormatter(), formatVersion: (name, version) => `${name} ${version}` })),", ` Effect.provide(Sdk.layer(process.env["${env}_URL"] ?? "http://127.0.0.1:8787", process.env["${env}_TOKEN"])),`, " Effect.provide(Layer.succeed(ExitCode, ExitCode.of({ set: (code) => Effect.sync(() => void (process.exitCode = code)) }))),", " Effect.provide(NodeServices.layer),", " NodeRuntime.runMain,", ");"),
29
+ };
30
+ };
31
+ export const renderCli = (model, name) => {
32
+ const session = sessionOperations(model);
33
+ const plain = Object.values(model.operations).filter((o) => o !== session?.signIn && o !== session?.show);
34
+ return [main(model, name), output(), ...plain.map(command), ...renderSessionCommands(model, name)];
35
+ };
@@ -0,0 +1,11 @@
1
+ import type { Model, OperationModel } from "@orthograph/compiler";
2
+ import type { RenderedFile } from "#modules/names/types.js";
3
+ /**
4
+ * The starter's identity things (`packages/preset`): the operation that signs in with email and password, and the one
5
+ * that says who is signed in. A project without both keeps every command as the operation declares it.
6
+ */
7
+ export declare const sessionOperations: (model: Model) => {
8
+ readonly signIn: OperationModel;
9
+ readonly show: OperationModel;
10
+ } | undefined;
11
+ export declare const renderSessionCommands: (model: Model, name: string) => ReadonlyArray<RenderedFile>;
@@ -0,0 +1,55 @@
1
+ import { flagCode, helpOf } from "#modules/names/service.js";
2
+ import { GENERATED, camel, lines } from "#modules/names/service.js";
3
+ /**
4
+ * The starter's identity things (`packages/preset`): the operation that signs in with email and password, and the one
5
+ * that says who is signed in. A project without both keeps every command as the operation declares it.
6
+ */
7
+ export const sessionOperations = (model) => {
8
+ const signIn = model.operations["session.sign-in"];
9
+ const show = model.operations["session.show"];
10
+ return signIn && show && signIn.kind === "operation" ? { signIn, show } : undefined;
11
+ };
12
+ const device = (name) => {
13
+ const env = name.toUpperCase().replace(/-/g, "_");
14
+ return {
15
+ path: "generated/cli/src/session/device.ts",
16
+ scaffold: false,
17
+ content: lines(GENERATED, "// Signing in by device code (RFC 8628) against Better Auth, and the session this machine keeps for each environment.", `import { Config, Console, Data, Duration, Effect, FileSystem, Option, Path, Schedule, Schema } from "effect";`, `import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";`, `import * as Sdk from "../../../sdk/src/index.ts";`, "", `const CLIENT = "${name}-cli";`, `const GRANT = "urn:ietf:params:oauth:grant-type:device_code";`, "", "export class NotSignedIn extends Data.TaggedError(\"NotSignedIn\")<{ readonly env: string }> {}", "export class DeviceRefused extends Data.TaggedError(\"DeviceRefused\")<{ readonly error: string }> {}", "/** The code isn't approved yet (`authorization_pending`), or the server wants fewer polls (`slow_down`). */", "class Waiting extends Data.TaggedError(\"Waiting\")<{ readonly slower: boolean }> {}", "", "const Started = Schema.Struct({ device_code: Schema.String, user_code: Schema.String, verification_uri_complete: Schema.String, expires_in: Schema.Number, interval: Schema.Number });", "const Issued = Schema.Struct({ access_token: Schema.String });", "const Refused = Schema.Struct({ error: Schema.String });", "const Sessions = Schema.Record(Schema.String, Schema.Struct({ url: Schema.String, token: Schema.String }));", "", `const baseUrl = Config.String("${env}_URL").pipe(Config.withDefault("http://127.0.0.1:8787"));`, "", `/** Where the sessions are kept: ${env}_CONFIG_DIR, else the user's config folder. */`, "const location = Effect.gen(function* () {", " const path = yield* Path.Path;", ` const dir = yield* Config.String("${env}_CONFIG_DIR").pipe(`, ` Config.orElse(() => Config.String("XDG_CONFIG_HOME").pipe(Config.map((base) => path.join(base, "${name}")))),`, ` Config.orElse(() => Config.String("HOME").pipe(Config.map((home) => path.join(home, ".config", "${name}")))),`, " );", " return { dir, file: path.join(dir, \"session.json\") };", "});", "", "const kept = Effect.gen(function* () {", " const fs = yield* FileSystem.FileSystem;", " const { file } = yield* location;", " if (!(yield* fs.exists(file))) return {} as typeof Sessions.Type;", " return yield* fs.readFileString(file).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Sessions))));", "});", "", "const keep = (env: string, session: { readonly url: string; readonly token: string }) =>", " Effect.gen(function* () {", " const fs = yield* FileSystem.FileSystem;", " const { dir, file } = yield* location;", " const all = yield* kept;", " yield* fs.makeDirectory(dir, { recursive: true, mode: 0o700 });", " yield* fs.writeFileString(file, JSON.stringify({ ...all, [env]: session }, null, 2) + \"\\n\", { mode: 0o600 });", " });", "", "/** The session kept for `env`, or `NotSignedIn`. */", "const saved = (env: string) =>", " Effect.flatMap(kept, (all) => { const s = all[env]; return s ? Effect.succeed(s) : Effect.fail(new NotSignedIn({ env })); });", "", "/** Run `effect` as the person signed in to `env`, against the server that signed them in. The token is never shown. */", "export const withSession = (env: string) => <A, E, R>(effect: Effect.Effect<A, E, R>) =>", " Effect.flatMap(saved(env), (s) => effect.pipe(Effect.provide(Sdk.layer(s.url, s.token))));", "", "/** The flags a command was given, without the ones it wasn't. */", "export const given = (flags: Readonly<Record<string, Option.Option<string>>>) =>", " Object.fromEntries(Object.entries(flags).flatMap(([key, value]) => (Option.isSome(value) ? [[key, value.value]] : [])));", "", "const post = (url: string, body: unknown) =>", " HttpClient.execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body))).pipe(", " Effect.flatMap((response) => Effect.map(response.json, (json) => ({ status: response.status, json }))),", " Effect.provide(FetchHttpClient.layer),", " );", "", "const refused = (json: unknown) =>", " Effect.fail(new DeviceRefused({ error: Option.match(Schema.decodeUnknownOption(Refused)(json), { onNone: () => \"unexpected answer\", onSome: (r) => r.error }) }));", "", "/** One poll: the token, or `Waiting`, or a refusal. */", "const poll = (url: string, deviceCode: string) =>", " post(`${url}/api/auth/device/token`, { grant_type: GRANT, device_code: deviceCode, client_id: CLIENT }).pipe(", " Effect.flatMap(({ status, json }): Effect.Effect<string, Waiting | DeviceRefused | Schema.SchemaError> => {", " if (status === 200) return Effect.map(Schema.decodeUnknownEffect(Issued)(json), (issued) => issued.access_token);", " const error = Option.match(Schema.decodeUnknownOption(Refused)(json), { onNone: () => \"\", onSome: (r) => r.error });", " return error === \"authorization_pending\" || error === \"slow_down\" ? Effect.fail(new Waiting({ slower: error === \"slow_down\" })) : refused(json);", " }),", " );", "", "/** Wait the server's interval between polls, and five seconds longer after each `slow_down`. */", "const spacing = (seconds: number) =>", " Schedule.fromStep(Effect.sync(() => {", " let wait = seconds;", " return (_now: number, last: unknown): Effect.Effect<[number, Duration.Duration]> =>", " Effect.sync(() => { if (last instanceof Waiting && last.slower) wait += 5; return [wait, Duration.seconds(wait)]; });", " }));", "", "/** Ask for a code, say where to approve it, poll until it is approved, and keep the session for `env`. */", "export const deviceSignIn = (env: string) =>", " Effect.gen(function* () {", " const url = yield* baseUrl;", " const started = yield* post(`${url}/api/auth/device/code`, { client_id: CLIENT }).pipe(", " Effect.flatMap(({ status, json }): Effect.Effect<typeof Started.Type, DeviceRefused | Schema.SchemaError> =>", " status === 200 ? Schema.decodeUnknownEffect(Started)(json) : refused(json)),", " );", " // The server names itself by its configured address; the person reaches it where this CLI did.", " const approval = new URL(started.verification_uri_complete);", " yield* Console.log(`code ${started.user_code}`);", " yield* Console.log(`approve at ${url}${approval.pathname}${approval.search}`);", " const token = yield* poll(url, started.device_code).pipe(", " Effect.retry({ schedule: spacing(started.interval), while: (e) => e instanceof Waiting }),", " Effect.timeoutOrElse({ duration: Duration.seconds(started.expires_in), orElse: () => Effect.fail(new DeviceRefused({ error: \"expired_token\" })) }),", " );", " yield* keep(env, { url, token });", " yield* Console.log(\"signed in\");", " });"),
18
+ };
19
+ };
20
+ const commands = (name, ops) => {
21
+ const flags = (op) => Object.entries(op.payload).map(([k, f]) => `${k}: ${flagCode(k, f)}.pipe(Flag.optional)`);
22
+ const env = (what) => `env: Flag.String("env").pipe(Flag.withMetavar("env"), Flag.withDescription(${JSON.stringify(what)}), Flag.optional)`;
23
+ const file = (op, doc, body) => ({
24
+ path: `generated/cli/src/${op.thing}/${op.verb}.ts`,
25
+ scaffold: false,
26
+ content: lines(GENERATED, `import { Effect, Option, Schema } from "effect";`, `import { Command, Flag } from "effect/cli";`, `import { declaration } from "../../../api/src/${op.thing}/${op.verb}.ts";`, `import * as Sdk from "../../../sdk/src/index.ts";`, `import { answer, refused } from "../output.ts";`, `import { deviceSignIn, given, withSession } from "./device.ts";`, "", `/** ${doc} Each flag is handed on as text; the declaration decodes it. \`--json\` prints the whole answer as JSON. */`, ...body),
27
+ });
28
+ const verb = (op) => `Sdk.${camel(op.thing)}.${camel(op.verb)}`;
29
+ const signIn = file(ops.signIn, `${ops.signIn.description} With \`--env <env>\`, sign in by device code instead: it prints a code and where to approve it, waits, and keeps the session for \`session show --env <env>\`.`, [
30
+ `export const ${camel(ops.signIn.verb)} = Command.make(`,
31
+ ` "${ops.signIn.verb}",`,
32
+ ` { ${[...flags(ops.signIn), env("Sign in by device code to this environment, and keep the session, instead of with the flags."), `json: Flag.Boolean("json").pipe(Flag.withDefault(false))`].join(", ")} },`,
33
+ " ({ json, env, ...flags }) =>",
34
+ " Effect.gen(function* () {",
35
+ " if (Option.isSome(env)) return yield* deviceSignIn(env.value).pipe(refused);",
36
+ ` return yield* Schema.decodeUnknownEffect(declaration.payloadSchema)(given(flags)).pipe(Effect.flatMap(${verb(ops.signIn)}), answer(json));`,
37
+ " }),",
38
+ `).pipe(Command.withDescription(${JSON.stringify(`${helpOf(ops.signIn)} With --env <env>, sign in by device code instead: it prints a code and where to approve it, waits, and keeps the session.`)}));`,
39
+ ]);
40
+ const show = file(ops.show, `${ops.show.description} With \`--env <env>\`, as the person that environment's session belongs to.`, [
41
+ `export const ${camel(ops.show.verb)} = Command.make(`,
42
+ ` "${ops.show.verb}",`,
43
+ ` { ${[...flags(ops.show), env("Ask as the person this environment's kept session belongs to."), `json: Flag.Boolean("json").pipe(Flag.withDefault(false))`].join(", ")} },`,
44
+ " ({ json, env, ...flags }) => {",
45
+ ` const run = Schema.decodeUnknownEffect(declaration.payloadSchema)(given(flags)).pipe(Effect.flatMap(${verb(ops.show)}));`,
46
+ " return Effect.gen(function* () { return Option.isSome(env) ? yield* withSession(env.value)(run) : yield* run; }).pipe(answer(json));",
47
+ " },",
48
+ `).pipe(Command.withDescription(${JSON.stringify(`${helpOf(ops.show)} With --env <env>, as the person that environment's session belongs to.`)}));`,
49
+ ]);
50
+ return [device(name), signIn, show];
51
+ };
52
+ export const renderSessionCommands = (model, name) => {
53
+ const ops = sessionOperations(model);
54
+ return ops ? commands(name, ops) : [];
55
+ };
@@ -0,0 +1,2 @@
1
+ /** The command line (`generated/cli/`): `<project> <thing> <verb> --<field> ...`, one command per operation, built on the SDK. */
2
+ export declare const cli: import("orthograph").Projection<{}>;
@@ -0,0 +1,10 @@
1
+ import { Blueprint, Host, Ships } from "orthograph";
2
+ import { modelOf, within } from "#modules/names/service.js";
3
+ import { renderCli } from "./internal/cli.js";
4
+ /** The command line (`generated/cli/`): `<project> <thing> <verb> --<field> ...`, one command per operation, built on the SDK. */
5
+ export const cli = Blueprint.projection({
6
+ description: "The command line: a command per operation, flags typed from its fields, built on the SDK.",
7
+ host: [Host.node],
8
+ ships: [Ships.release],
9
+ render: (input) => within(input, "cli", renderCli(modelOf(input), input.name)),
10
+ });
@@ -0,0 +1 @@
1
+ export type { Projection } from "orthograph";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { Model, OperationModel } from "@orthograph/compiler";
2
+ /** The body's sections in order, each a list of lines; the scaffold puts an empty line between them. */
3
+ export declare const body: (model: Model, op: OperationModel, minted: string | undefined) => ReadonlyArray<ReadonlyArray<string>>;
4
+ /** Whether the body uses `Match` and `Outcome`: a move with more than one outcome. */
5
+ export declare const branches: (op: OperationModel) => boolean;
@@ -0,0 +1,79 @@
1
+ import { an, label, refusalsOf } from "./words.js";
2
+ const runner = (key) => (/^[A-Za-z_$][\w$]*$/.test(key) ? `steps.${key}` : `steps[${JSON.stringify(key)}]`);
3
+ const property = (key) => (/^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key));
4
+ const blank = (what, type = "") => `Handlers.blank${type ? `<${type}>` : ""}(${JSON.stringify(what)})`;
5
+ const stepBlock = (model, op, key) => {
6
+ const step = op.steps[key];
7
+ const store = step.type === "database" ? (step.writes?.length ? step.writes.join(", ") : model.things[op.thing]?.store) : undefined;
8
+ return [
9
+ ` // Step ${key}: ${step.type}${store ? `, in the store ${store}` : ""}, span ${step.name}.`,
10
+ ` yield* ${runner(key)}(${blank(`${key}: the work this step does`)});${step.optional ? " // optional: may be skipped" : ""}`,
11
+ ];
12
+ };
13
+ const refusalBlocks = (model, op) => refusalsOf(model, op).filter((r) => r.giver === "yours").map((r) => {
14
+ const fields = r.fieldModels;
15
+ const made = Object.keys(fields).length === 0
16
+ ? [` return yield* new ${r.name}({});`]
17
+ : [
18
+ ` return yield* new ${r.name}({`,
19
+ ...Object.entries(fields).map(([k, f]) => ` ${property(k)}: yield* ${blank(`${r.name}.${k}, ${an(label(f))}`)},`),
20
+ " });",
21
+ ];
22
+ return [
23
+ ` // ${r.name}: exit ${r.exit}, ${r.code}.`,
24
+ ` if (yield* ${blank(`refuse ${r.name} when?`, "boolean")}) {`,
25
+ ` yield* Effect.logInfo(yield* ${blank(`why ${r.name} was refused`)});`,
26
+ ...made,
27
+ " }",
28
+ ];
29
+ });
30
+ /** What can follow from a state: every move whose `from` holds it. */
31
+ const nextFrom = (model, op, state) => {
32
+ const moves = Object.entries(model.things[op.thing]?.machine?.moves ?? {}).filter(([, m]) => m.from.includes(state));
33
+ return moves.length === 0 ? "nothing more" : moves.map(([k, m]) => `${k} (to ${m.to.join(" or ")})`).join(", ");
34
+ };
35
+ const moveBlock = (model, op) => {
36
+ const move = op.move;
37
+ if (!move)
38
+ return [];
39
+ const from = move.from.length ? `, from ${move.from.join(" or ")}` : "";
40
+ if (move.to.length === 1)
41
+ return [` // The move ${move.key}${from}, to ${move.to[0]}.`, " yield* move();"];
42
+ return [
43
+ ` // The move ${move.key}${from}: one branch per outcome. A new outcome won't compile until it has its branch.`,
44
+ ` const outcome = yield* ${blank(`where ${move.key} ends: ${move.to.join(" or ")}`, "Outcome")};`,
45
+ " yield* Match.value(outcome).pipe(",
46
+ ...move.to.flatMap((to) => [
47
+ ` // To ${to}. From there the ${op.thing} can: ${nextFrom(model, op, to)}.`,
48
+ ` Match.when(${JSON.stringify(to)}, () => move(${JSON.stringify(to)})),`,
49
+ ]),
50
+ " Match.exhaustive,",
51
+ " );",
52
+ ];
53
+ };
54
+ const answerBlock = (model, op, minted) => {
55
+ const fields = Object.entries(op.answer);
56
+ if (fields.length === 0)
57
+ return [" return {};"];
58
+ const event = op.move ? model.things[op.thing]?.events[op.move.emits] : undefined;
59
+ const own = model.things[op.thing]?.fields ?? {};
60
+ return [
61
+ " return {",
62
+ ...fields.flatMap(([k, f]) => [
63
+ ...(event && k in event && !(k in own) && !(k in op.payload) ? [` // ${op.move.emits} needs ${k}, and only the answer can give it.`] : []),
64
+ ` ${property(k)}: ${k === minted ? "id" : `yield* ${blank(`${k}, ${an(label(f))}`)}`},`,
65
+ ]),
66
+ " };",
67
+ ];
68
+ };
69
+ /** The body's sections in order, each a list of lines; the scaffold puts an empty line between them. */
70
+ export const body = (model, op, minted) => {
71
+ const keys = Object.keys(op.steps);
72
+ const writing = keys.findIndex((k) => (op.steps[k].writes?.length ?? 0) > 0);
73
+ const at = writing >= 0 ? writing : keys.length > 0 ? keys.length - 1 : keys.length;
74
+ const steps = keys.map((k) => stepBlock(model, op, k));
75
+ return [...steps.slice(0, at), ...refusalBlocks(model, op), ...steps.slice(at), moveBlock(model, op), answerBlock(model, op, minted)]
76
+ .filter((s) => s.length > 0);
77
+ };
78
+ /** Whether the body uses `Match` and `Outcome`: a move with more than one outcome. */
79
+ export const branches = (op) => (op.move?.to.length ?? 0) > 1;
@@ -0,0 +1,17 @@
1
+ import type { Model, OperationModel } from "@orthograph/compiler";
2
+ import type { RenderedFile } from "#modules/names/types.js";
3
+ /** The call steps of an operation: the step's key, and the mount and call it reaches. */
4
+ export declare const callSteps: (op: OperationModel) => {
5
+ mount: string;
6
+ call: string;
7
+ mode: "promise" | "effect";
8
+ key: string;
9
+ }[];
10
+ /** The server's imports of every callable and layer its operations wire, once each. */
11
+ export declare const callImports: (model: Model) => ReadonlyArray<string>;
12
+ /** `, calls: { price: { run, layer } }` for `Handlers.serve`, or nothing for an operation that calls nothing. */
13
+ export declare const wired: (model: Model, op: OperationModel) => string;
14
+ /** Where a handler of an operation that calls takes its type from. */
15
+ export declare const handlerTypeAt: (op: OperationModel) => string;
16
+ /** The handler's type for an operation that calls an adapter: each call step typed by the callable it runs. */
17
+ export declare const renderHandlerTypes: (model: Model) => ReadonlyArray<RenderedFile>;
@@ -0,0 +1,80 @@
1
+ // What an operation that calls an adapter needs generated beside it: the callable and the adapter's layer wired into the
2
+ // served operation (generated/server), and the handler's type, which carries the callable's own types (also in
3
+ // generated/server, so no foreign type ever reaches generated/api or generated/sdk, which clients import).
4
+ //
5
+ // A generated adapter (G16-adapter-mounts call 1) has no `src/calls/`: its call runs the package's `client`, given the mount's
6
+ // address (`ORTHO_STAND_<MOUNT>`, else `<MOUNT>_BASE_URL`) and key (`<MOUNT>_API_KEY`) from the Worker's environment. No address
7
+ // is a defect the runner raises before anything is sent; nothing ever defaults to the description's `servers`.
8
+ import { Names } from "orthograph/server";
9
+ import { GENERATED, camel, declarationAt, lines, pascal } from "#modules/names/service.js";
10
+ /** The call steps of an operation: the step's key, and the mount and call it reaches. */
11
+ export const callSteps = (op) => Object.entries(op.steps).flatMap(([key, step]) => (step.call ? [{ key, ...step.call }] : []));
12
+ /**
13
+ * A call's name as part of a variable's: one-to-one, so two calls never share a variable. A group's `.` is `$$`, and any other
14
+ * character a name can't hold is `$<its code in hex>$` (`quotes.get` is `quotes$$get`, `users:search` is `users$3a$search`):
15
+ * read left to right, `$$` is a dot and `$` before hex opens an escape, so no two names give one variable. A name of
16
+ * letters, digits and `_` only, every name in the repo before generated adapters, is as it was.
17
+ */
18
+ const ident = (call) => call.replace(/[^A-Za-z0-9_]/g, (c) => (c === "." ? "$$" : `$${c.codePointAt(0).toString(16)}$`));
19
+ const callVar = (mount, call) => `${camel(mount)}${pascal(ident(call))}Call`;
20
+ const layerVar = (mount) => `${camel(mount)}Layer`;
21
+ const clientVar = (mount) => `${camel(mount)}Client`;
22
+ const callable = (model, mount, call) => `${model.mounts?.[mount]?.package ?? mount}/src/calls/${call}.js`;
23
+ /** A mount's name as its environment's variables spell it: `fx-backup` is `FX_BACKUP`. */
24
+ const envName = (mount) => mount.toUpperCase().replaceAll("-", "_");
25
+ /** A mount of a generated adapter: its plugin declares the `baseUrl` secret, which only the adapter generator writes. */
26
+ const generatedMount = (model, mount) => Object.values(model.secrets ?? {}).some((s) => s.export === "baseUrl" && s.from.kind !== "app" && s.from.mount === mount);
27
+ /** The server's imports of every callable and layer its operations wire, once each. */
28
+ export const callImports = (model) => {
29
+ const steps = Object.values(model.operations).flatMap(callSteps);
30
+ const calls = [...new Map(steps.map((s) => [callVar(s.mount, s.call), s]))];
31
+ const layers = [...new Set(steps.filter((s) => model.mounts?.[s.mount]?.layer).map((s) => s.mount))];
32
+ const clients = [...new Set(steps.map((s) => s.mount))].filter((m) => generatedMount(model, m)).sort();
33
+ return [
34
+ ...calls.filter(([, s]) => !generatedMount(model, s.mount)).map(([name, s]) => `import ${name} from "${callable(model, s.mount, s.call)}";`),
35
+ ...layers.map((m) => `import { layer as ${layerVar(m)} } from "${model.mounts[m].package}/src/layer.js";`),
36
+ ...(clients.length === 0 ? [] : [
37
+ `import { env as callEnv } from "cloudflare:workers";`,
38
+ ...clients.map((m) => `import { client as ${clientVar(m)} } from "${model.mounts[m].package}/client";`),
39
+ "/** The Worker's variables, which give each generated adapter's mount its address and key. */",
40
+ "const callVars = callEnv as unknown as Readonly<Record<string, string | undefined>>;",
41
+ ]),
42
+ ...clients.map((m) => {
43
+ const [stand, base, key] = [`ORTHO_STAND_${envName(m)}`, `${envName(m)}_BASE_URL`, `${envName(m)}_API_KEY`];
44
+ return `const ${camel(m)}Address = () => callVars["${stand}"] || callVars["${base}"];\n`
45
+ + `const ${camel(m)}Calls = () => ${clientVar(m)}({ baseUrl: ${camel(m)}Address()!, ...(callVars["${key}"] ? { token: callVars["${key}"] } : {}) }).calls as unknown as Readonly<Record<string, any>>;`;
46
+ }),
47
+ ...calls.filter(([, s]) => generatedMount(model, s.mount)).map(([name, s]) => `const ${name} = { run: (input?: Readonly<Record<string, unknown>>) => ${camel(s.mount)}Calls()${s.call.split(".").map((p) => `[${JSON.stringify(p)}]`).join("")}(input), unset: () => (${camel(s.mount)}Address() ? undefined : "${envName(s.mount)}_BASE_URL") };`),
48
+ ];
49
+ };
50
+ /** `, calls: { price: { run, layer } }` for `Handlers.serve`, or nothing for an operation that calls nothing. */
51
+ export const wired = (model, op) => {
52
+ const steps = callSteps(op);
53
+ if (steps.length === 0)
54
+ return "";
55
+ const one = (s) => generatedMount(model, s.mount)
56
+ ? `${s.key}: ${callVar(s.mount, s.call)}`
57
+ : `${s.key}: { run: ${callVar(s.mount, s.call)}${model.mounts?.[s.mount]?.layer ? `, layer: ${layerVar(s.mount)}` : ""} }`;
58
+ return `, calls: { ${steps.map(one).join(", ")} }`;
59
+ };
60
+ /** Where a handler of an operation that calls takes its type from. */
61
+ export const handlerTypeAt = (op) => `generated/server/handlers/${op.thing}/${op.verb}.ts`;
62
+ /** The handler's type for an operation that calls an adapter: each call step typed by the callable it runs. */
63
+ export const renderHandlerTypes = (model) => {
64
+ // Some environment's clock is stepped or scaled (K23): the runtime then provides `Timers` to handlers.
65
+ const timed = Object.values(model.environments ?? {}).some((e) => e.clock !== undefined && e.clock.kind !== "real");
66
+ return Object.values(model.operations).flatMap((op) => {
67
+ const steps = callSteps(op);
68
+ if (op.kind !== "operation" || steps.length === 0)
69
+ return [];
70
+ const path = handlerTypeAt(op);
71
+ return [{
72
+ path,
73
+ scaffold: false,
74
+ content: lines(GENERATED, "// What the handler is given: its payload, and its steps, each call typed by the callable it runs.", `import type { SqlClient } from "effect/sql";`, `import type { Auth, Handler as Of, Records${timed ? ", Timers" : ""} } from "${Names.pkg("language-effect")}";`, `import type declaration from "${declarationAt(path, op.file)}";`, steps.map((s) => generatedMount(model, s.mount)
75
+ // A generated adapter's call takes one flat input object and settles to the answer's JSON (its `client`).
76
+ ? `declare const ${camel(s.key)}Call: (input?: Readonly<Record<string, unknown>>) => Promise<unknown>;`
77
+ : `import type ${camel(s.key)}Call from "${callable(model, s.mount, s.call)}";`), "", `export type Handler<R = Records | SqlClient.SqlClient | Auth${timed ? " | Timers" : ""}> = Of<typeof declaration, R, { ${steps.map((s) => `${s.key}: typeof ${camel(s.key)}Call`).join(", ")} }>;`),
78
+ }];
79
+ });
80
+ };
@@ -0,0 +1,18 @@
1
+ import type { Model, OperationModel } from "@orthograph/compiler";
2
+ /** What the runtime reads before the handler and hands in (K16 g): the subject, each referenced thing, a minted id. */
3
+ export interface HandedIn {
4
+ /** The payload field naming the operation's own thing by id. */
5
+ readonly subject: string | undefined;
6
+ /** Each other payload field that references a thing's id, with that thing. */
7
+ readonly refs: ReadonlyArray<{
8
+ readonly field: string;
9
+ readonly thing: string;
10
+ }>;
11
+ /** The move creates, so the runtime mints the new instance's id. */
12
+ readonly mints: boolean;
13
+ }
14
+ export declare const handedIn: (model: Model, op: OperationModel) => HandedIn;
15
+ /** Who may call, each `allowed` entry with its role's rule, citing the roles file (shared with the journey stubs). */
16
+ export declare const whoLines: (model: Model, op: OperationModel, title?: string) => string[];
17
+ /** The doc block, `/**` to `*\/`, with each part separated by an empty line. */
18
+ export declare const header: (model: Model, op: OperationModel) => ReadonlyArray<string>;
@@ -0,0 +1,106 @@
1
+ import { timeMoveOf, whenWords } from "#modules/names/service.js";
2
+ import { allowedFile, callerOf, columns, label, listed, refusalsOf, ruleOf, seenBy, thingFile, who } from "./words.js";
3
+ const referenced = (model, ref) => {
4
+ if (!ref)
5
+ return undefined;
6
+ const [thing, field] = ref.split(".");
7
+ if (!thing || !field)
8
+ return undefined;
9
+ if (field === "id")
10
+ return thing;
11
+ const deeper = model.things[thing]?.fields[field]?.ref;
12
+ return deeper?.endsWith(".id") ? deeper.slice(0, -3) : undefined;
13
+ };
14
+ export const handedIn = (model, op) => {
15
+ const fields = Object.entries(op.payload);
16
+ const subject = fields.find(([, f]) => f.ref === `${op.thing}.id`)?.[0];
17
+ const refs = fields.flatMap(([field, f]) => {
18
+ const thing = field === subject ? undefined : referenced(model, f.ref);
19
+ return thing ? [{ field, thing }] : [];
20
+ });
21
+ return { subject, refs, mints: op.move !== null && op.move.from.length === 0 };
22
+ };
23
+ const fieldLines = (title, file, empty, fields) => Object.keys(fields).length === 0
24
+ ? [empty]
25
+ : [`${title}, from ${file}:`, ...columns(Object.entries(fields).map(([k, f]) => [k, `${label(f)}${f.optional ? " (optional)" : ""}${seenBy(f)}`])).map((l) => ` ${l}`)];
26
+ /** Who may call, each `allowed` entry with its role's rule, citing the roles file (shared with the journey stubs). */
27
+ export const whoLines = (model, op, title = "Who may call") => {
28
+ const files = [...new Set(op.allowed.map((a) => allowedFile(model, op, a)))];
29
+ const one = files.length === 1;
30
+ return [
31
+ one ? `${title}, from ${files[0]}:` : `${title}:`,
32
+ ...op.allowed.map((a) => {
33
+ const rule = ruleOf(model, a);
34
+ return ` ${callerOf(a)}${rule ? `: ${rule}` : ""}${one ? "" : `; from ${allowedFile(model, op, a)}`}`;
35
+ }),
36
+ ];
37
+ };
38
+ const refusalLines = (model, op) => {
39
+ const rows = refusalsOf(model, op);
40
+ return rows.length === 0
41
+ ? ["Refusals: none."]
42
+ : ["Refusals:", ...columns(rows.map((r) => [r.name, `exit ${r.exit}`, r.code, `${r.said}; from ${r.file}`])).map((l) => ` ${l}`)];
43
+ };
44
+ const machineLines = (model, op) => {
45
+ const machine = model.things[op.thing]?.machine;
46
+ if (!machine)
47
+ return [];
48
+ const rows = Object.entries(machine.moves).flatMap(([key, m]) => (m.from.length ? m.from : ["(creates)"]).flatMap((from) => m.to.map((to) => ({ mark: key === op.move?.key, cells: [from, key, to, m.emits] }))));
49
+ const table = columns([["from", "move", "to", "emits"], ...rows.map((r) => r.cells)]);
50
+ return [
51
+ `The ${op.thing}'s machine, from ${thingFile(model, op.thing, "machine")} (${op.move ? "▶ marks this call" : "this call makes no move"}):`,
52
+ ...table.map((l, i) => ` ${i > 0 && rows[i - 1].mark ? "▶" : " "} ${l}`),
53
+ ];
54
+ };
55
+ /** Where each field of the move's event comes from: the answer, else the payload, else the instance as the call left it. */
56
+ const eventSources = (model, op, emits) => {
57
+ const fields = Object.keys(model.things[op.thing]?.events[emits] ?? {});
58
+ const source = (f) => f in op.answer ? "the answer" : f in op.payload ? "the payload" : f in (model.things[op.thing]?.fields ?? {}) ? `the ${op.thing} as the call left it` : "nothing";
59
+ const groups = new Map();
60
+ for (const f of fields)
61
+ groups.set(source(f), [...(groups.get(source(f)) ?? []), f]);
62
+ return [...groups].map(([from, fs]) => `${listed(fs)} from ${from}`).join(", ");
63
+ };
64
+ const runtimeLines = (model, op) => {
65
+ const machine = model.things[op.thing]?.machine;
66
+ const hands = handedIn(model, op);
67
+ const gated = op.allowed.some((a) => a.kind !== "anyone");
68
+ const caller = op.allowed.every((a) => a.kind === "signed-in") ? "signed in" : who(op);
69
+ const steps = Object.values(op.steps).map((s) => s.name);
70
+ const event = op.move ? eventSources(model, op, op.move.emits) : "";
71
+ const said = [
72
+ gated ? `before it runs, it refuses NotAllowed unless the caller is ${caller}` : "",
73
+ op.move?.from.length && machine ? `before it runs, it refuses ${machine.notFrom.error} unless the ${op.thing} is in ${op.move.from.join(" or ")}` : "",
74
+ hands.subject ? `before it runs, it hands in the ${op.thing} it read as subject, so this handler never reads it again` : "",
75
+ ...hands.refs.map((r) => {
76
+ const missing = `${model.things[r.thing]?.identifier ?? r.thing}NotFound`;
77
+ return `before it runs, it reads the ${r.field} and hands it in as refs.${r.field}${op.refusals.includes(missing) ? `, refusing ${missing} if there is none` : ""}`;
78
+ }),
79
+ hands.mints ? `before it runs, it mints the ${op.thing}'s new id and hands it in as id` : "",
80
+ steps.length ? `each step is its own span: ${steps.join(", ")}` : "",
81
+ op.move ? `once it answers, it sets the ${op.thing}'s state to ${op.move.to.length > 1 ? "the outcome given to move" : op.move.to[0]}` : "",
82
+ op.move ? `once it answers, it writes ${op.move.emits}${event ? `: ${event}` : ""}` : "",
83
+ `the call is the span ${op.name}, and its commit ${op.name}.commit`,
84
+ ].filter(Boolean);
85
+ return ["What the runtime does, so this handler doesn't:", ...said.map((s, i) => ` ${s}${i === said.length - 1 ? "." : ";"}`)];
86
+ };
87
+ /** The doc block, `/**` to `*\/`, with each part separated by an empty line. */
88
+ export const header = (model, op) => {
89
+ const promises = [
90
+ op.idempotent === "request" ? `Idempotent by request, from ${op.file}: the same request key from the same caller is one call.` : "",
91
+ timeMoveOf(model, op) ? `Made by time, from ${thingFile(model, op.thing, "machine")}: ${whenWords(op.thing, timeMoveOf(model, op), "")}.` : "",
92
+ op.budget ? `Budget, from ${op.file}: p95 ${op.budget.p95Ms}ms.` : "",
93
+ ].filter(Boolean);
94
+ const parts = [
95
+ [`${op.name}: ${op.description}`],
96
+ whoLines(model, op),
97
+ fieldLines("Payload", op.file, "Payload: none.", op.payload),
98
+ fieldLines("Answer", op.file, "Answer: nothing.", op.answer),
99
+ refusalLines(model, op),
100
+ promises,
101
+ machineLines(model, op),
102
+ runtimeLines(model, op),
103
+ ].filter((p) => p.length > 0);
104
+ const body = parts.flatMap((p, i) => (i === 0 ? p : ["", ...p]));
105
+ return ["/**", ...body.flatMap((l) => l.split("\n")).map((l) => (l === "" ? " *" : ` * ${l.replaceAll("*/", "*\\/")}`)), " */"];
106
+ };