@geekmidas/constructs 10.0.0-alpha.21 → 10.0.0-alpha.23
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 +29 -23
- package/dist/{Endpoint-DbYQJgb-.d.cts → Endpoint-CrhoafsT.d.cts} +2 -2
- package/dist/{Endpoint-BxkRWQ8G.d.mts.map → Endpoint-CrhoafsT.d.cts.map} +1 -1
- package/dist/{Endpoint-BxkRWQ8G.d.mts → Endpoint-pTZrMs_h.d.mts} +2 -2
- package/dist/{Endpoint-DbYQJgb-.d.cts.map → Endpoint-pTZrMs_h.d.mts.map} +1 -1
- package/dist/{EndpointFactory-T06kTFHg.d.mts → EndpointFactory-BSLH4hSU.d.mts} +2 -2
- package/dist/{EndpointFactory-DE6nKtFZ.d.cts.map → EndpointFactory-BSLH4hSU.d.mts.map} +1 -1
- package/dist/{EndpointFactory-DE6nKtFZ.d.cts → EndpointFactory-CiCzFdMx.d.cts} +2 -2
- package/dist/{EndpointFactory-T06kTFHg.d.mts.map → EndpointFactory-CiCzFdMx.d.cts.map} +1 -1
- package/dist/Queue-BB2-DgqJ.cjs +123 -0
- package/dist/Queue-BB2-DgqJ.cjs.map +1 -0
- package/dist/Queue-Dfumm1WR.mjs +118 -0
- package/dist/Queue-Dfumm1WR.mjs.map +1 -0
- package/dist/Topic-BaNCgP61.cjs +107 -0
- package/dist/Topic-BaNCgP61.cjs.map +1 -0
- package/dist/Topic-QqnO_6Dl.mjs +102 -0
- package/dist/Topic-QqnO_6Dl.mjs.map +1 -0
- package/dist/adaptors/aws.d.cts +1 -1
- package/dist/adaptors/aws.d.mts +1 -1
- package/dist/adaptors/hono.d.cts +1 -1
- package/dist/adaptors/hono.d.mts +1 -1
- package/dist/adaptors/testing.cjs +136 -32
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +101 -13
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +101 -13
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +133 -33
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/{auth-BlO8MUkR.d.cts → auth-BR2eYxIW.d.cts} +16 -1
- package/dist/{auth-BlO8MUkR.d.cts.map → auth-BR2eYxIW.d.cts.map} +1 -1
- package/dist/{auth-CHWIdcQO.d.mts → auth-DtprqoJP.d.mts} +16 -1
- package/dist/{auth-CHWIdcQO.d.mts.map → auth-DtprqoJP.d.mts.map} +1 -1
- package/dist/auth.cjs +28 -6
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +1 -1
- package/dist/auth.d.mts +1 -1
- package/dist/auth.mjs +28 -6
- package/dist/auth.mjs.map +1 -1
- package/dist/endpoints/index.d.cts +2 -2
- package/dist/endpoints/index.d.mts +2 -2
- package/dist/queue/index.cjs +3 -116
- package/dist/queue/index.cjs.map +1 -1
- package/dist/queue/index.mjs +1 -114
- package/dist/queue/index.mjs.map +1 -1
- package/dist/rest-api.d.cts +2 -2
- package/dist/rest-api.d.mts +2 -2
- package/dist/topic/index.cjs +3 -100
- package/dist/topic/index.cjs.map +1 -1
- package/dist/topic/index.mjs +1 -98
- package/dist/topic/index.mjs.map +1 -1
- package/package.json +31 -31
package/dist/auth.mjs
CHANGED
|
@@ -90,9 +90,9 @@ var BetterAuth = class {
|
|
|
90
90
|
* the app never writes those tables and never gets to drift from them.
|
|
91
91
|
*/
|
|
92
92
|
async migrations(options) {
|
|
93
|
-
const
|
|
93
|
+
const resolved = await this.optionsFor(options, { owner: true });
|
|
94
94
|
const { getMigrations } = await import("better-auth/db/migration");
|
|
95
|
-
const { runMigrations } = await getMigrations(
|
|
95
|
+
const { runMigrations } = await getMigrations(resolved);
|
|
96
96
|
return runMigrations;
|
|
97
97
|
}
|
|
98
98
|
/**
|
|
@@ -139,7 +139,30 @@ var BetterAuth = class {
|
|
|
139
139
|
}
|
|
140
140
|
return { app };
|
|
141
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* The ids of the better-auth plugins this server runs — what a client has
|
|
144
|
+
* to pair its own plugins with (`magic-link` with `magicLinkClient`).
|
|
145
|
+
* Resolved the way the server resolves them, options callback included.
|
|
146
|
+
*/
|
|
147
|
+
async pluginIds(options) {
|
|
148
|
+
const { plugins = [] } = await this.configured(options);
|
|
149
|
+
return plugins.map(({ id }) => id);
|
|
150
|
+
}
|
|
151
|
+
/** Better-auth's options as given — a value, or a callback of the environment. */
|
|
152
|
+
async configured(options) {
|
|
153
|
+
const configure = this.config.options;
|
|
154
|
+
return typeof configure === "function" ? await configure(options) : configure ?? {};
|
|
155
|
+
}
|
|
142
156
|
async connect(options, as = {}) {
|
|
157
|
+
return betterAuth(await this.optionsFor(options, as));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Everything better-auth is given: the app's options, and what the construct
|
|
161
|
+
* owns — its secret, its URL, its tenant's connection, the origins and cookie
|
|
162
|
+
* domain its graph derives. One place, so the server and its migrations are
|
|
163
|
+
* built from the same options.
|
|
164
|
+
*/
|
|
165
|
+
async optionsFor(options, as = {}) {
|
|
143
166
|
const { secret, baseUrl, trustedOrigins, cookieDomain } = options.envParser.create((get) => ({
|
|
144
167
|
secret: get(this.keys.secret).string(),
|
|
145
168
|
baseUrl: get(this.keys.url).string(),
|
|
@@ -148,9 +171,8 @@ var BetterAuth = class {
|
|
|
148
171
|
})).parse();
|
|
149
172
|
const tenant = this.config.database;
|
|
150
173
|
const db = await (as.owner && tenant.owner ? tenant.owner : tenant.service).register(options);
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
return betterAuth({
|
|
174
|
+
const configured = await this.configured(options);
|
|
175
|
+
return {
|
|
154
176
|
...configured,
|
|
155
177
|
secret,
|
|
156
178
|
baseURL: baseUrl,
|
|
@@ -168,7 +190,7 @@ var BetterAuth = class {
|
|
|
168
190
|
...configured.advanced?.crossSubDomainCookies
|
|
169
191
|
} } : {}
|
|
170
192
|
}
|
|
171
|
-
}
|
|
193
|
+
};
|
|
172
194
|
}
|
|
173
195
|
};
|
|
174
196
|
/** The auth server answered a session check with something other than 200. */
|
package/dist/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * `BetterAuth` — a declared auth server.\n *\n * It is three things at once, which is what makes it the construct that\n * exercises most of the model: a consumer of a database, a producer of an\n * authorizer, and a set of endpoints. This lands the first two.\n *\n * Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`\n * — rather than one it invents. The tenant declares the schema and the role;\n * this declares the one thing left, the signing secret, and reads back the keys\n * it needs.\n *\n * :::caution\n * The isolation that arrangement is *for* — the application's own role holding\n * no grant on these tables, so a compromised handler cannot read sessions — does\n * **not hold yet**. No target creates the per-schema role: both connect as the\n * database owner, so today the tenant is a `search_path`, which is a namespace\n * and not a privilege boundary. See \"Roles are declared and never created\" in\n * `docs/design/constructs-outstanding.md`.\n * :::\n *\n * It declares its own surface, so where it answers, who may call it, and the\n * domain its cookies are scoped to all arrive as environment resolved by the\n * target — none of them guessed from a port, and none of them listed by hand in\n * application config.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tenvironmentCase,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { betterAuth } from 'better-auth';\nimport type { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport {\n\ttype Authenticator,\n\ttype Construct,\n\ttype Consumable,\n\tedgeTo,\n} from './construct-interface';\n\n/** The server better-auth hands back. */\nexport type AuthServer = ReturnType<typeof betterAuth>;\n\n/** A signed-in session as better-auth hands it back: `{ user, session }`. */\nexport type AuthSession = AuthServer['$Infer']['Session'];\n\n/** Everything better-auth takes, minus what the construct owns. */\nexport type BetterAuthOptions = Omit<\n\tParameters<typeof betterAuth>[0],\n\t'database' | 'secret' | 'basePath' | 'baseURL'\n>;\n\nexport interface BetterAuthConfig<TDatabase extends Consumable> {\n\t/**\n\t * The schema tenant its tables live in.\n\t *\n\t * A construct rather than a URL: the tenant already declares its schema and\n\t * its role, and taking the declaration is what puts the edge in the graph\n\t * instead of a connection string in two places.\n\t */\n\tdatabase: TDatabase;\n\t/**\n\t * The app that serves this auth server, relative to the workspace root —\n\t * `'apps/auth'`.\n\t *\n\t * Required, for the reason `RestApi.path` is. Not to be confused with\n\t * `basePath`, which is where its routes are mounted in a URL.\n\t */\n\tpath: string;\n\t/**\n\t * Where the auth routes are mounted, e.g. `/api/auth`.\n\t *\n\t * Structural — it is part of the URL every client calls, so it cannot differ\n\t * between stages the way the host can.\n\t */\n\tbasePath?: string;\n\t/**\n\t * The rest of better-auth's options: providers, plugins, email settings.\n\t *\n\t * A function when they need another construct — a magic-link plugin has to\n\t * *send* the link, and the thing that sends mail is a construct whose client\n\t * has to be registered. It is handed the same `ServiceRegisterOptions` this\n\t * construct was, so the env parser flows through the graph rather than being\n\t * imported out of application config.\n\t */\n\toptions?:\n\t\t| BetterAuthOptions\n\t\t| ((\n\t\t\t\toptions: ServiceRegisterOptions,\n\t\t ) => BetterAuthOptions | Promise<BetterAuthOptions>);\n}\n\nconst DEFAULT_BASE_PATH = '/api/auth';\n\nexport class BetterAuth<\n\tTName extends string = string,\n\tTDatabase extends Consumable = Consumable,\n> implements Construct<TName, AuthServer>, Authenticator<AuthSession>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, AuthServer>;\n\treadonly basePath: string;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the server reads cannot drift.\n\t */\n\tprivate readonly keys: {\n\t\tsecretId: string;\n\t\tsecret: string;\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: BetterAuthConfig<TDatabase>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.basePath = config.basePath ?? DEFAULT_BASE_PATH;\n\n\t\t// A secret's name is its key: `Auth` signs with `AUTH_SECRET`, which is\n\t\t// also what better-auth's own tooling looks for.\n\t\tconst secretId = `${canonical}Secret`;\n\t\tthis.keys = {\n\t\t\tsecretId,\n\t\t\tsecret: environmentCase(secretId),\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\t/**\n\t * A signing secret and a surface.\n\t *\n\t * The database is *not* declared here — the tenant that was passed in\n\t * declares it, and declaring it twice is the duplication the whole model\n\t * removes. What is declared is what this construct owns: the key it signs\n\t * with, and the routes it answers on.\n\t *\n\t * One endpoint, wildcarded. Better Auth routes internally and the set of\n\t * paths depends on which capabilities are enabled, so enumerating them here\n\t * would be a copy of its router that goes stale on its next release. The\n\t * surface's job is to send everything under `basePath` to one handler, which\n\t * is exactly what the declaration says.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'secret',\n\t\t\t\tid: this.keys.secretId,\n\t\t\t\tprovides: [this.keys.secret],\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t\tendpoints: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `${this.id}Handler`,\n\t\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t\tmethod: 'ANY',\n\t\t\t\t\t\tpath: `${this.basePath}/*`,\n\t\t\t\t\t\t// Read off the tenant rather than written down: this\n\t\t\t\t\t\t// construct takes whatever database it is given, and a\n\t\t\t\t\t\t// hardcoded kind is a second statement of a fact the\n\t\t\t\t\t\t// tenant already makes.\n\t\t\t\t\t\tdependencies: [edgeTo(this.config.database)],\n\t\t\t\t\t\trequires: [this.keys.secret],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Whose request this is: the session for these headers, or `null`.\n\t *\n\t * Asked of the auth server over HTTP, at the URL the `.auth()` edge injects —\n\t * so it is the same call whether the server runs in this process, beside\n\t * it, or behind MSW in a test. Only the session headers are forwarded; the\n\t * surface decides which.\n\t */\n\tasync verify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<AuthSession | null> {\n\t\tconst { url } = envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\n\t\tconst response = await fetch(`${url}${this.basePath}/get-session`, {\n\t\t\theaders,\n\t\t});\n\n\t\t// Better Auth answers `null` for a request with no session. Anything\n\t\t// other than a 200 is the server failing, which is not the same thing as\n\t\t// \"signed out\" and must not be read as it.\n\t\tif (!response.ok) {\n\t\t\tthrow new SessionCheckFailed(this.id, response.status);\n\t\t}\n\n\t\treturn (await response.json()) as AuthSession | null;\n\t}\n\n\t/**\n\t * Better Auth's own migrations, for the app's migrate step.\n\t *\n\t * It brings its own schema — users, sessions, accounts, verifications — so\n\t * the app never writes those tables and never gets to drift from them.\n\t */\n\tasync migrations(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<() => Promise<void>> {\n\t\t// As the owner, not the runtime role. Creating tables is DDL, and the\n\t\t// whole point of the split is that a handler's role cannot do it — so a\n\t\t// migrator that connected the way a handler does would fail on the first\n\t\t// `CREATE TABLE` rather than working by accident.\n\t\tconst auth = await this.connect(options, { owner: true });\n\t\t// better-auth 1.7 split the migration builder out of `better-auth/db`\n\t\t// into its own entry, so importing it no longer drags the whole db layer\n\t\t// in behind it.\n\t\tconst { getMigrations } = await import('better-auth/db/migration');\n\t\tconst { runMigrations } = await getMigrations(auth.options);\n\n\t\treturn runMigrations;\n\t}\n\n\t/**\n\t * The server this surface runs as, built from its own declaration.\n\t *\n\t * A surface is a deploy unit, so something has to serve it, and the thing\n\t * that knows how is the construct — not a generator writing a mount into\n\t * somebody else's entry point. That is how the auth server came to be\n\t * mounted by a hook in the application it was supposed to be separate from,\n\t * and then to be served by nothing at all when the hook was deleted.\n\t *\n\t * The routes come from {@link declare}: one wildcard under `basePath`, read\n\t * off the same declaration the manifest carries, so the surface the graph\n\t * describes and the surface that answers requests cannot disagree.\n\t *\n\t * ```ts\n\t * // .gkm/server/app.ts — the whole generated entry\n\t * import { auth } from '@acme/constructs/auth.js';\n\t * export const { app } = await auth.server({ envParser });\n\t * ```\n\t */\n\tasync server(options: ServiceRegisterOptions): Promise<{ app: Hono }> {\n\t\tconst { Hono } = await import('hono');\n\t\tconst { cors } = await import('hono/cors');\n\t\tconst app = new Hono();\n\t\tconst server = await this.connect(options);\n\n\t\t// Who may call this surface, read off the graph. The same list Better\n\t\t// Auth checks for CSRF — it arrives as `<ID>_TRUSTED_ORIGINS`, composed\n\t\t// by the target from whatever declared an edge to this construct, so a\n\t\t// site that depends on the auth server is allowed to reach it and\n\t\t// nothing else is. Nobody writes an origin down.\n\t\tconst { origins } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tapp.use('*', cors({ origin: origins, credentials: true, maxAge: 3600 }));\n\n\t\t// Read off the declaration rather than restated here. `ANY` is every\n\t\t// method Better Auth routes internally, which is the reason the\n\t\t// declaration wildcards rather than enumerating.\n\t\tconst [surface] = this.declare().filter(\n\t\t\t(d): d is Extract<Declaration, { kind: 'rest-api' }> =>\n\t\t\t\td.kind === 'rest-api',\n\t\t);\n\n\t\tfor (const endpoint of surface?.endpoints ?? []) {\n\t\t\tconst methods =\n\t\t\t\tendpoint.method === 'ANY'\n\t\t\t\t\t? (['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const)\n\t\t\t\t\t: ([endpoint.method] as const);\n\n\t\t\tapp.on([...methods], endpoint.path, (c) => server.handler(c.req.raw));\n\t\t}\n\n\t\treturn { app };\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<AuthServer> {\n\t\tconst { secret, baseUrl, trustedOrigins, cookieDomain } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\tsecret: get(this.keys.secret).string(),\n\t\t\t\t// The surface's own URL, resolved by the target — not guessed from\n\t\t\t\t// a port, which was wrong the moment the server moved to 3001.\n\t\t\t\tbaseUrl: get(this.keys.url).string(),\n\t\t\t\t// Better Auth's CSRF check applies to every caller, not just\n\t\t\t\t// browsers, so an API calling the auth server is rejected unless\n\t\t\t\t// its origin is trusted. The list is derived from the graph and\n\t\t\t\t// arrives as one comma-separated value, for the same reason every\n\t\t\t\t// other derived value arrives as a string: it crosses a process\n\t\t\t\t// boundary as env.\n\t\t\t\ttrustedOrigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t\t// The domain a session cookie has to carry to be readable by a\n\t\t\t\t// frontend on a sibling host. Optional because there is often\n\t\t\t\t// nothing to widen to: locally everything shares `localhost`,\n\t\t\t\t// where cookies ignore the port and a `Domain` would only be a\n\t\t\t\t// value the browser refuses.\n\t\t\t\tcookieDomain: get(this.keys.cookieDomain).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\t// The tenant's own client: one construct, one connection, so what auth\n\t\t// writes and what the browser inspects cannot be two different databases.\n\t\t// A migration asks the tenant for its owner connection, which the tenant\n\t\t// exposes as a `Service` and not as anything `.dependsOn()` would take.\n\t\tconst tenant = this.config.database as Consumable & {\n\t\t\towner?: Service<string, unknown>;\n\t\t};\n\t\tconst source = as.owner && tenant.owner ? tenant.owner : tenant.service;\n\n\t\tconst db = (await source.register(options)) as Kysely<\n\t\t\tRecord<string, never>\n\t\t>;\n\n\t\t// Hoisted: narrowing a property of `this` is not preserved across the\n\t\t// await, and the false branch is the plain-object form.\n\t\tconst configure = this.config.options;\n\t\tconst configured: BetterAuthOptions =\n\t\t\ttypeof configure === 'function'\n\t\t\t\t? await configure(options)\n\t\t\t\t: (configure ?? {});\n\n\t\t// `Auth<O>` is invariant in its options in better-auth 1.7, so the value\n\t\t// built from a concrete literal is not assignable to the `AuthServer`\n\t\t// alias, which names the constraint. The runtime object is the same one\n\t\t// either way; the assertion keeps the variance where it happens instead\n\t\t// of spreading a generic through the construct's public type.\n\t\treturn betterAuth({\n\t\t\t...configured,\n\t\t\tsecret,\n\t\t\tbaseURL: baseUrl,\n\t\t\tbasePath: this.basePath,\n\t\t\tdatabase: { db, type: 'postgres' },\n\t\t\t// Whatever the app added wins over the derived list rather than\n\t\t\t// replacing it: an origin nobody declared is still sometimes real.\n\t\t\ttrustedOrigins: [\n\t\t\t\t...trustedOrigins,\n\t\t\t\t...(configured.trustedOrigins &&\n\t\t\t\tArray.isArray(configured.trustedOrigins)\n\t\t\t\t\t? configured.trustedOrigins\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tadvanced: {\n\t\t\t\t...configured.advanced,\n\t\t\t\t// Only when a domain was derived. Better Auth reads the presence\n\t\t\t\t// of this block as intent, so enabling it with no domain would\n\t\t\t\t// widen the cookie to whatever host happened to set it — and the\n\t\t\t\t// case with nothing to widen to is the common one, not an error.\n\t\t\t\t...(cookieDomain\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcrossSubDomainCookies: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tdomain: cookieDomain,\n\t\t\t\t\t\t\t\t...configured.advanced?.crossSubDomainCookies,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t}) as AuthServer;\n\t}\n}\n\n/** The auth server answered a session check with something other than 200. */\nexport class SessionCheckFailed extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' answered a session check with ${status}. ` +\n\t\t\t\t`A request with no session gets 200 and null; this is the server ` +\n\t\t\t\t`failing — check that it is running and reachable at its URL.`,\n\t\t);\n\t\tthis.name = 'SessionCheckFailed';\n\t}\n}\n"],"mappings":";;;;AAmGA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAIA;CAmBmB;CAlBlB;CACA;CACA;;;;;CAMA;CAQA,YACC,IACA,QACC;EADgB,KAAA,SAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,WAAW,OAAO,YAAY;EAInC,MAAM,WAAW,GAAG,UAAU;EAC9B,KAAK,OAAO;GACX;GACA,QAAQ,gBAAgB,QAAQ;GAChC,KAAK,WAAW,WAAW,KAAK;GAChC,gBAAgB,WAAW,WAAW,gBAAgB;GACtD,cAAc,WAAW,WAAW,cAAc;EACnD;EAGA,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,YAAY,KAAK,QAAQ,OAAO;EAC5C;CACD;;;;;;;;;;;;;;;CAg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AM,SAAS,KAAK,OAAO;EAK3B,MAAM,KAAM,OAFG,GAAG,SAAS,OAAO,QAAQ,OAAO,QAAQ,OAAO,QAAA,CAEvC,SAAS,OAAO;EAMzC,MAAM,YAAY,KAAK,OAAO;EAC9B,MAAM,aACL,OAAO,cAAc,aAClB,MAAM,UAAU,OAAO,IACtB,aAAa,CAAC;EAOnB,OAAO,WAAW;GACjB,GAAG;GACH;GACA,SAAS;GACT,UAAU,KAAK;GACf,UAAU;IAAE;IAAI,MAAM;GAAW;GAGjC,gBAAgB,CACf,GAAG,gBACH,GAAI,WAAW,kBACf,MAAM,QAAQ,WAAW,cAAc,IACpC,WAAW,iBACX,CAAC,CACL;GACA,UAAU;IACT,GAAG,WAAW;IAKd,GAAI,eACD,EACA,uBAAuB;KACtB,SAAS;KACT,QAAQ;KACR,GAAG,WAAW,UAAU;IACzB,EACD,IACC,CAAC;GACL;EACD,CAAC;CACF;AACD;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CAEnC;CACA;CAFV,YACC,eACA,QACC;EACD,MACC,IAAI,cAAc,kCAAkC,OAAO,+HAG5D;EAPS,KAAA,gBAAA;EACA,KAAA,SAAA;EAOT,KAAK,OAAO;CACb;AACD"}
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * `BetterAuth` — a declared auth server.\n *\n * It is three things at once, which is what makes it the construct that\n * exercises most of the model: a consumer of a database, a producer of an\n * authorizer, and a set of endpoints. This lands the first two.\n *\n * Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`\n * — rather than one it invents. The tenant declares the schema and the role;\n * this declares the one thing left, the signing secret, and reads back the keys\n * it needs.\n *\n * :::caution\n * The isolation that arrangement is *for* — the application's own role holding\n * no grant on these tables, so a compromised handler cannot read sessions — does\n * **not hold yet**. No target creates the per-schema role: both connect as the\n * database owner, so today the tenant is a `search_path`, which is a namespace\n * and not a privilege boundary. See \"Roles are declared and never created\" in\n * `docs/design/constructs-outstanding.md`.\n * :::\n *\n * It declares its own surface, so where it answers, who may call it, and the\n * domain its cookies are scoped to all arrive as environment resolved by the\n * target — none of them guessed from a port, and none of them listed by hand in\n * application config.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tenvironmentCase,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { betterAuth } from 'better-auth';\nimport type { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport {\n\ttype Authenticator,\n\ttype Construct,\n\ttype Consumable,\n\tedgeTo,\n} from './construct-interface';\n\n/** The server better-auth hands back. */\nexport type AuthServer = ReturnType<typeof betterAuth>;\n\n/** A signed-in session as better-auth hands it back: `{ user, session }`. */\nexport type AuthSession = AuthServer['$Infer']['Session'];\n\n/** Everything better-auth takes, minus what the construct owns. */\nexport type BetterAuthOptions = Omit<\n\tParameters<typeof betterAuth>[0],\n\t'database' | 'secret' | 'basePath' | 'baseURL'\n>;\n\nexport interface BetterAuthConfig<TDatabase extends Consumable> {\n\t/**\n\t * The schema tenant its tables live in.\n\t *\n\t * A construct rather than a URL: the tenant already declares its schema and\n\t * its role, and taking the declaration is what puts the edge in the graph\n\t * instead of a connection string in two places.\n\t */\n\tdatabase: TDatabase;\n\t/**\n\t * The app that serves this auth server, relative to the workspace root —\n\t * `'apps/auth'`.\n\t *\n\t * Required, for the reason `RestApi.path` is. Not to be confused with\n\t * `basePath`, which is where its routes are mounted in a URL.\n\t */\n\tpath: string;\n\t/**\n\t * Where the auth routes are mounted, e.g. `/api/auth`.\n\t *\n\t * Structural — it is part of the URL every client calls, so it cannot differ\n\t * between stages the way the host can.\n\t */\n\tbasePath?: string;\n\t/**\n\t * The rest of better-auth's options: providers, plugins, email settings.\n\t *\n\t * A function when they need another construct — a magic-link plugin has to\n\t * *send* the link, and the thing that sends mail is a construct whose client\n\t * has to be registered. It is handed the same `ServiceRegisterOptions` this\n\t * construct was, so the env parser flows through the graph rather than being\n\t * imported out of application config.\n\t */\n\toptions?:\n\t\t| BetterAuthOptions\n\t\t| ((\n\t\t\t\toptions: ServiceRegisterOptions,\n\t\t ) => BetterAuthOptions | Promise<BetterAuthOptions>);\n}\n\nconst DEFAULT_BASE_PATH = '/api/auth';\n\nexport class BetterAuth<\n\tTName extends string = string,\n\tTDatabase extends Consumable = Consumable,\n> implements Construct<TName, AuthServer>, Authenticator<AuthSession>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, AuthServer>;\n\treadonly basePath: string;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the server reads cannot drift.\n\t */\n\tprivate readonly keys: {\n\t\tsecretId: string;\n\t\tsecret: string;\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: BetterAuthConfig<TDatabase>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.basePath = config.basePath ?? DEFAULT_BASE_PATH;\n\n\t\t// A secret's name is its key: `Auth` signs with `AUTH_SECRET`, which is\n\t\t// also what better-auth's own tooling looks for.\n\t\tconst secretId = `${canonical}Secret`;\n\t\tthis.keys = {\n\t\t\tsecretId,\n\t\t\tsecret: environmentCase(secretId),\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\t/**\n\t * A signing secret and a surface.\n\t *\n\t * The database is *not* declared here — the tenant that was passed in\n\t * declares it, and declaring it twice is the duplication the whole model\n\t * removes. What is declared is what this construct owns: the key it signs\n\t * with, and the routes it answers on.\n\t *\n\t * One endpoint, wildcarded. Better Auth routes internally and the set of\n\t * paths depends on which capabilities are enabled, so enumerating them here\n\t * would be a copy of its router that goes stale on its next release. The\n\t * surface's job is to send everything under `basePath` to one handler, which\n\t * is exactly what the declaration says.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'secret',\n\t\t\t\tid: this.keys.secretId,\n\t\t\t\tprovides: [this.keys.secret],\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t\tendpoints: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `${this.id}Handler`,\n\t\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t\tmethod: 'ANY',\n\t\t\t\t\t\tpath: `${this.basePath}/*`,\n\t\t\t\t\t\t// Read off the tenant rather than written down: this\n\t\t\t\t\t\t// construct takes whatever database it is given, and a\n\t\t\t\t\t\t// hardcoded kind is a second statement of a fact the\n\t\t\t\t\t\t// tenant already makes.\n\t\t\t\t\t\tdependencies: [edgeTo(this.config.database)],\n\t\t\t\t\t\trequires: [this.keys.secret],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Whose request this is: the session for these headers, or `null`.\n\t *\n\t * Asked of the auth server over HTTP, at the URL the `.auth()` edge injects —\n\t * so it is the same call whether the server runs in this process, beside\n\t * it, or behind MSW in a test. Only the session headers are forwarded; the\n\t * surface decides which.\n\t */\n\tasync verify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<AuthSession | null> {\n\t\tconst { url } = envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\n\t\tconst response = await fetch(`${url}${this.basePath}/get-session`, {\n\t\t\theaders,\n\t\t});\n\n\t\t// Better Auth answers `null` for a request with no session. Anything\n\t\t// other than a 200 is the server failing, which is not the same thing as\n\t\t// \"signed out\" and must not be read as it.\n\t\tif (!response.ok) {\n\t\t\tthrow new SessionCheckFailed(this.id, response.status);\n\t\t}\n\n\t\treturn (await response.json()) as AuthSession | null;\n\t}\n\n\t/**\n\t * Better Auth's own migrations, for the app's migrate step.\n\t *\n\t * It brings its own schema — users, sessions, accounts, verifications — so\n\t * the app never writes those tables and never gets to drift from them.\n\t */\n\tasync migrations(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<() => Promise<void>> {\n\t\t// As the owner, not the runtime role. Creating tables is DDL, and the\n\t\t// whole point of the split is that a handler's role cannot do it — so a\n\t\t// migrator that connected the way a handler does would fail on the first\n\t\t// `CREATE TABLE` rather than working by accident.\n\t\t//\n\t\t// The options, not a server built from them: better-auth checks its\n\t\t// schema when a server starts, and before the migration that creates the\n\t\t// tables it can only report them missing — an error in every migrate\n\t\t// log, about the very tables the next line creates.\n\t\tconst resolved = await this.optionsFor(options, { owner: true });\n\t\t// better-auth 1.7 split the migration builder out of `better-auth/db`\n\t\t// into its own entry, so importing it no longer drags the whole db layer\n\t\t// in behind it.\n\t\tconst { getMigrations } = await import('better-auth/db/migration');\n\t\tconst { runMigrations } = await getMigrations(resolved);\n\n\t\treturn runMigrations;\n\t}\n\n\t/**\n\t * The server this surface runs as, built from its own declaration.\n\t *\n\t * A surface is a deploy unit, so something has to serve it, and the thing\n\t * that knows how is the construct — not a generator writing a mount into\n\t * somebody else's entry point. That is how the auth server came to be\n\t * mounted by a hook in the application it was supposed to be separate from,\n\t * and then to be served by nothing at all when the hook was deleted.\n\t *\n\t * The routes come from {@link declare}: one wildcard under `basePath`, read\n\t * off the same declaration the manifest carries, so the surface the graph\n\t * describes and the surface that answers requests cannot disagree.\n\t *\n\t * ```ts\n\t * // .gkm/server/app.ts — the whole generated entry\n\t * import { auth } from '@acme/constructs/auth.js';\n\t * export const { app } = await auth.server({ envParser });\n\t * ```\n\t */\n\tasync server(options: ServiceRegisterOptions): Promise<{ app: Hono }> {\n\t\tconst { Hono } = await import('hono');\n\t\tconst { cors } = await import('hono/cors');\n\t\tconst app = new Hono();\n\t\tconst server = await this.connect(options);\n\n\t\t// Who may call this surface, read off the graph. The same list Better\n\t\t// Auth checks for CSRF — it arrives as `<ID>_TRUSTED_ORIGINS`, composed\n\t\t// by the target from whatever declared an edge to this construct, so a\n\t\t// site that depends on the auth server is allowed to reach it and\n\t\t// nothing else is. Nobody writes an origin down.\n\t\tconst { origins } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tapp.use('*', cors({ origin: origins, credentials: true, maxAge: 3600 }));\n\n\t\t// Read off the declaration rather than restated here. `ANY` is every\n\t\t// method Better Auth routes internally, which is the reason the\n\t\t// declaration wildcards rather than enumerating.\n\t\tconst [surface] = this.declare().filter(\n\t\t\t(d): d is Extract<Declaration, { kind: 'rest-api' }> =>\n\t\t\t\td.kind === 'rest-api',\n\t\t);\n\n\t\tfor (const endpoint of surface?.endpoints ?? []) {\n\t\t\tconst methods =\n\t\t\t\tendpoint.method === 'ANY'\n\t\t\t\t\t? (['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const)\n\t\t\t\t\t: ([endpoint.method] as const);\n\n\t\t\tapp.on([...methods], endpoint.path, (c) => server.handler(c.req.raw));\n\t\t}\n\n\t\treturn { app };\n\t}\n\n\t/**\n\t * The ids of the better-auth plugins this server runs — what a client has\n\t * to pair its own plugins with (`magic-link` with `magicLinkClient`).\n\t * Resolved the way the server resolves them, options callback included.\n\t */\n\tasync pluginIds(options: ServiceRegisterOptions): Promise<string[]> {\n\t\tconst { plugins = [] } = await this.configured(options);\n\t\treturn plugins.map(({ id }) => id);\n\t}\n\n\t/** Better-auth's options as given — a value, or a callback of the environment. */\n\tprivate async configured(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<BetterAuthOptions> {\n\t\t// Hoisted: narrowing a property of `this` is not preserved across the\n\t\t// await, and the false branch is the plain-object form.\n\t\tconst configure = this.config.options;\n\t\treturn typeof configure === 'function'\n\t\t\t? await configure(options)\n\t\t\t: (configure ?? {});\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<AuthServer> {\n\t\t// `Auth<O>` is invariant in its options in better-auth 1.7, so the value\n\t\t// built from a concrete literal is not assignable to the `AuthServer`\n\t\t// alias, which names the constraint. The runtime object is the same one\n\t\t// either way; the assertion keeps the variance where it happens instead\n\t\t// of spreading a generic through the construct's public type.\n\t\treturn betterAuth(await this.optionsFor(options, as)) as AuthServer;\n\t}\n\n\t/**\n\t * Everything better-auth is given: the app's options, and what the construct\n\t * owns — its secret, its URL, its tenant's connection, the origins and cookie\n\t * domain its graph derives. One place, so the server and its migrations are\n\t * built from the same options.\n\t */\n\tprivate async optionsFor(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Parameters<typeof betterAuth>[0]> {\n\t\tconst { secret, baseUrl, trustedOrigins, cookieDomain } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\tsecret: get(this.keys.secret).string(),\n\t\t\t\t// The surface's own URL, resolved by the target — not guessed from\n\t\t\t\t// a port, which was wrong the moment the server moved to 3001.\n\t\t\t\tbaseUrl: get(this.keys.url).string(),\n\t\t\t\t// Better Auth's CSRF check applies to every caller, not just\n\t\t\t\t// browsers, so an API calling the auth server is rejected unless\n\t\t\t\t// its origin is trusted. The list is derived from the graph and\n\t\t\t\t// arrives as one comma-separated value, for the same reason every\n\t\t\t\t// other derived value arrives as a string: it crosses a process\n\t\t\t\t// boundary as env.\n\t\t\t\ttrustedOrigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t\t// The domain a session cookie has to carry to be readable by a\n\t\t\t\t// frontend on a sibling host. Optional because there is often\n\t\t\t\t// nothing to widen to: locally everything shares `localhost`,\n\t\t\t\t// where cookies ignore the port and a `Domain` would only be a\n\t\t\t\t// value the browser refuses.\n\t\t\t\tcookieDomain: get(this.keys.cookieDomain).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\t// The tenant's own client: one construct, one connection, so what auth\n\t\t// writes and what the browser inspects cannot be two different databases.\n\t\t// A migration asks the tenant for its owner connection, which the tenant\n\t\t// exposes as a `Service` and not as anything `.dependsOn()` would take.\n\t\tconst tenant = this.config.database as Consumable & {\n\t\t\towner?: Service<string, unknown>;\n\t\t};\n\t\tconst source = as.owner && tenant.owner ? tenant.owner : tenant.service;\n\n\t\tconst db = (await source.register(options)) as Kysely<\n\t\t\tRecord<string, never>\n\t\t>;\n\n\t\tconst configured = await this.configured(options);\n\n\t\treturn {\n\t\t\t...configured,\n\t\t\tsecret,\n\t\t\tbaseURL: baseUrl,\n\t\t\tbasePath: this.basePath,\n\t\t\tdatabase: { db, type: 'postgres' },\n\t\t\t// Whatever the app added wins over the derived list rather than\n\t\t\t// replacing it: an origin nobody declared is still sometimes real.\n\t\t\ttrustedOrigins: [\n\t\t\t\t...trustedOrigins,\n\t\t\t\t...(configured.trustedOrigins &&\n\t\t\t\tArray.isArray(configured.trustedOrigins)\n\t\t\t\t\t? configured.trustedOrigins\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tadvanced: {\n\t\t\t\t...configured.advanced,\n\t\t\t\t// Only when a domain was derived. Better Auth reads the presence\n\t\t\t\t// of this block as intent, so enabling it with no domain would\n\t\t\t\t// widen the cookie to whatever host happened to set it — and the\n\t\t\t\t// case with nothing to widen to is the common one, not an error.\n\t\t\t\t...(cookieDomain\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcrossSubDomainCookies: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tdomain: cookieDomain,\n\t\t\t\t\t\t\t\t...configured.advanced?.crossSubDomainCookies,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** The auth server answered a session check with something other than 200. */\nexport class SessionCheckFailed extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' answered a session check with ${status}. ` +\n\t\t\t\t`A request with no session gets 200 and null; this is the server ` +\n\t\t\t\t`failing — check that it is running and reachable at its URL.`,\n\t\t);\n\t\tthis.name = 'SessionCheckFailed';\n\t}\n}\n"],"mappings":";;;;AAmGA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAIA;CAmBmB;CAlBlB;CACA;CACA;;;;;CAMA;CAQA,YACC,IACA,QACC;EADgB,KAAA,SAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,WAAW,OAAO,YAAY;EAInC,MAAM,WAAW,GAAG,UAAU;EAC9B,KAAK,OAAO;GACX;GACA,QAAQ,gBAAgB,QAAQ;GAChC,KAAK,WAAW,WAAW,KAAK;GAChC,gBAAgB,WAAW,WAAW,gBAAgB;GACtD,cAAc,WAAW,WAAW,cAAc;EACnD;EAGA,KAAK,UAAU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2
2
|
import { t as Construct } from "../Construct-DTqYvkPG.cjs";
|
|
3
|
-
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-
|
|
4
|
-
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-
|
|
3
|
+
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-CrhoafsT.cjs";
|
|
4
|
+
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-CiCzFdMx.cjs";
|
|
5
5
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
6
6
|
import { EventPublisher, MappedEvent } from "@geekmidas/events";
|
|
7
7
|
import { Logger } from "@geekmidas/logger";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as StandardSchemaV1 } from "../index-CeEtxDmK.mjs";
|
|
2
2
|
import { t as Construct } from "../Construct-pVadmURD.mjs";
|
|
3
|
-
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-
|
|
4
|
-
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-
|
|
3
|
+
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-pTZrMs_h.mjs";
|
|
4
|
+
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-BSLH4hSU.mjs";
|
|
5
5
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
6
6
|
import { EventPublisher, MappedEvent } from "@geekmidas/events";
|
|
7
7
|
import { Service, ServiceDiscovery } from "@geekmidas/services";
|
package/dist/queue/index.cjs
CHANGED
|
@@ -1,121 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_Construct = require("../Construct-yG9Sw-5p.cjs");
|
|
3
2
|
const require_construct_interface = require("../construct-interface.cjs");
|
|
4
3
|
const require_clone = require("../clone-UGJpvQnL.cjs");
|
|
5
|
-
|
|
4
|
+
const require_Queue = require("../Queue-BB2-DgqJ.cjs");
|
|
6
5
|
let _geekmidas_logger_console = require("@geekmidas/logger/console");
|
|
7
|
-
let _geekmidas_events = require("@geekmidas/events");
|
|
8
|
-
//#region src/queue/Queue.ts
|
|
9
|
-
/**
|
|
10
|
-
* A queue worker — a point-to-point SQS-style queue and its single consumer.
|
|
11
|
-
* Unlike a `Subscriber` (topic fan-out, filtered by `subscribedEvents`), a queue
|
|
12
|
-
* drains every message of its one `message` type. Build one with `q` (see
|
|
13
|
-
* `QueueBuilder`); `gkm build` discovers it into the manifest's `queues` field.
|
|
14
|
-
*
|
|
15
|
-
* The producer side is {@link Queue.publisher} — a ready-to-inject `Service`
|
|
16
|
-
* that any endpoint/function drops into `.services([...])` to send messages.
|
|
17
|
-
*/
|
|
18
|
-
var Queue = class extends require_Construct.Construct {
|
|
19
|
-
name;
|
|
20
|
-
handler;
|
|
21
|
-
messageSchema;
|
|
22
|
-
timeout;
|
|
23
|
-
services;
|
|
24
|
-
logger;
|
|
25
|
-
batchSize;
|
|
26
|
-
fifo;
|
|
27
|
-
__IS_QUEUE__ = true;
|
|
28
|
-
static isQueue(obj) {
|
|
29
|
-
return Boolean(obj && obj.__IS_QUEUE__ === true && obj.type === "dev.geekmidas.function.queue");
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* The canonical id this queue is declared under.
|
|
33
|
-
*
|
|
34
|
-
* Derived from the name rather than given separately, so `emails` and
|
|
35
|
-
* `Emails` are one queue. The name stays what it was: it is the wire `type`
|
|
36
|
-
* a producer sends and the worker subscribes to, and changing that would
|
|
37
|
-
* silently orphan in-flight messages.
|
|
38
|
-
*/
|
|
39
|
-
id;
|
|
40
|
-
/**
|
|
41
|
-
* The producer's env key. Read by both {@link declare} and
|
|
42
|
-
* {@link publisher}, so what the target publishes and what the producer
|
|
43
|
-
* looks up cannot drift.
|
|
44
|
-
*/
|
|
45
|
-
connectionKey;
|
|
46
|
-
constructor(name, handler, messageSchema, timeout = 3e4, services = [], logger = _geekmidas_logger_console.DEFAULT_LOGGER, batchSize, fifo, constructs = []) {
|
|
47
|
-
super("dev.geekmidas.function.queue", logger, services, [], void 0, void 0, timeout, void 0, void 0, constructs);
|
|
48
|
-
this.name = name;
|
|
49
|
-
this.handler = handler;
|
|
50
|
-
this.messageSchema = messageSchema;
|
|
51
|
-
this.timeout = timeout;
|
|
52
|
-
this.services = services;
|
|
53
|
-
this.logger = logger;
|
|
54
|
-
this.batchSize = batchSize;
|
|
55
|
-
this.fifo = fifo;
|
|
56
|
-
this.id = (0, _geekmidas_manifest.canonicalId)(name);
|
|
57
|
-
this.connectionKey = (0, _geekmidas_manifest.provideKey)(this.id, "publisherConnectionString");
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* What this queue is in the manifest.
|
|
61
|
-
*
|
|
62
|
-
* A queue is a resource, not a handler: the worker is reached *through* it,
|
|
63
|
-
* so the declaration carries the producer's key and nothing about the code
|
|
64
|
-
* that drains it. The local target reads this to know which broker has to be
|
|
65
|
-
* running and what connection string to inject.
|
|
66
|
-
*/
|
|
67
|
-
declare() {
|
|
68
|
-
return [{
|
|
69
|
-
kind: "queue",
|
|
70
|
-
id: this.id,
|
|
71
|
-
provides: [this.connectionKey],
|
|
72
|
-
...this.fifo ? { fifo: true } : {},
|
|
73
|
-
worker: {
|
|
74
|
-
id: `${this.id}Worker`,
|
|
75
|
-
handler: `${this.id}.handler`,
|
|
76
|
-
dependencies: []
|
|
77
|
-
}
|
|
78
|
-
}];
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* The producer side — a `Service` exposing an `EventPublisher` typed to this
|
|
82
|
-
* queue's message. Inject it via `.services([queue.publisher])`; the handler
|
|
83
|
-
* then calls `services.<name>Publisher.publish([{ type, payload }])`.
|
|
84
|
-
*
|
|
85
|
-
* It reads `<NAME>_PUBLISHER_CONNECTION_STRING` and builds the transport from
|
|
86
|
-
* the URL protocol — `pgboss://` locally, `sqs://` deployed — so the same
|
|
87
|
-
* code publishes to Postgres in dev and SQS in prod. Because it's a `Service`,
|
|
88
|
-
* `Construct.getEnvironment()` sniffs it, so the env requirement flows into
|
|
89
|
-
* the manifest and infra links exactly this queue with least privilege.
|
|
90
|
-
*/
|
|
91
|
-
/**
|
|
92
|
-
* The queue as a dependency — what `.dependsOn([emailsQueue])` dissolves
|
|
93
|
-
* into, reachable as `services.emails`.
|
|
94
|
-
*
|
|
95
|
-
* It is the producer: a consumer is the worker written right here, so the
|
|
96
|
-
* only thing another construct can want from a queue is the ability to send
|
|
97
|
-
* to it. {@link publisher} is the same service under its older
|
|
98
|
-
* `<name>Publisher` key, kept for `.services([queue.publisher])`.
|
|
99
|
-
*/
|
|
100
|
-
get service() {
|
|
101
|
-
const { register } = this.publisher;
|
|
102
|
-
return {
|
|
103
|
-
serviceName: (0, _geekmidas_manifest.serviceKey)(this.id),
|
|
104
|
-
register
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
get publisher() {
|
|
108
|
-
const envVar = this.connectionKey;
|
|
109
|
-
return {
|
|
110
|
-
serviceName: `${this.name}Publisher`,
|
|
111
|
-
async register({ envParser }) {
|
|
112
|
-
const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
|
|
113
|
-
return _geekmidas_events.Publisher.fromConnectionString(connectionString);
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
};
|
|
118
|
-
//#endregion
|
|
119
6
|
//#region src/queue/QueueBuilder.ts
|
|
120
7
|
/**
|
|
121
8
|
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
|
@@ -179,14 +66,14 @@ var QueueBuilder = class {
|
|
|
179
66
|
handle(fn) {
|
|
180
67
|
if (!this._name) throw new Error("Queue requires a name — call .queue(name) before .handle().");
|
|
181
68
|
if (!this._messageSchema) throw new Error("Queue requires a message schema — call .message(schema) before .handle().");
|
|
182
|
-
return new Queue(this._name, fn, this._messageSchema, this._timeout, this._services, this._logger, this._batchSize, this._fifo, this._constructs);
|
|
69
|
+
return new require_Queue.Queue(this._name, fn, this._messageSchema, this._timeout, this._services, this._logger, this._batchSize, this._fifo, this._constructs);
|
|
183
70
|
}
|
|
184
71
|
};
|
|
185
72
|
//#endregion
|
|
186
73
|
//#region src/queue/index.ts
|
|
187
74
|
const q = new QueueBuilder();
|
|
188
75
|
//#endregion
|
|
189
|
-
exports.Queue = Queue;
|
|
76
|
+
exports.Queue = require_Queue.Queue;
|
|
190
77
|
exports.QueueBuilder = QueueBuilder;
|
|
191
78
|
exports.q = q;
|
|
192
79
|
|
package/dist/queue/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Construct","DEFAULT_LOGGER","canonicalId","provideKey","serviceKey","Publisher","DEFAULT_LOGGER","cloneWith","servicesOf","idsOf"],"sources":["../../src/queue/Queue.ts","../../src/queue/QueueBuilder.ts","../../src/queue/index.ts"],"sourcesContent":["import {\n\ttype EventPublisher,\n\ttype EventPublisherConnectionString,\n\ttype PublishableMessage,\n\tPublisher,\n} from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Construct, ConstructType } from '../Construct';\n\n/**\n * The wire message a queue carries: `{ type: <queue name>, payload: <message> }`.\n * The producer publishes this shape and the worker receives the `payload`s as\n * its `messages`. Typing `type` to the queue name keeps the publisher fully\n * typed and lets pg-boss (local) / SQS (deployed) route by name.\n */\nexport type QueueMessage<\n\tTName extends string,\n\tTMessage extends StandardSchemaV1,\n> = PublishableMessage<TName, InferStandardSchema<TMessage>>;\n\n/**\n * A queue worker — a point-to-point SQS-style queue and its single consumer.\n * Unlike a `Subscriber` (topic fan-out, filtered by `subscribedEvents`), a queue\n * drains every message of its one `message` type. Build one with `q` (see\n * `QueueBuilder`); `gkm build` discovers it into the manifest's `queues` field.\n *\n * The producer side is {@link Queue.publisher} — a ready-to-inject `Service`\n * that any endpoint/function drops into `.services([...])` to send messages.\n */\nexport class Queue<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 = StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> extends Construct<TLogger, string, undefined, undefined, TServices> {\n\t__IS_QUEUE__ = true;\n\n\tstatic isQueue(\n\t\tobj: unknown,\n\t): obj is Queue<string, StandardSchemaV1, Service[], Logger> {\n\t\treturn Boolean(\n\t\t\tobj &&\n\t\t\t\t(obj as { __IS_QUEUE__?: boolean }).__IS_QUEUE__ === true &&\n\t\t\t\t(obj as Construct).type === ConstructType.Queue,\n\t\t);\n\t}\n\n\t/**\n\t * The canonical id this queue is declared under.\n\t *\n\t * Derived from the name rather than given separately, so `emails` and\n\t * `Emails` are one queue. The name stays what it was: it is the wire `type`\n\t * a producer sends and the worker subscribes to, and changing that would\n\t * silently orphan in-flight messages.\n\t */\n\treadonly id: string;\n\n\t/**\n\t * The producer's env key. Read by both {@link declare} and\n\t * {@link publisher}, so what the target publishes and what the producer\n\t * looks up cannot drift.\n\t */\n\tprivate readonly connectionKey: string;\n\n\tconstructor(\n\t\tpublic readonly name: TName,\n\t\tpublic readonly handler: QueueHandler<TMessage, TServices, TLogger>,\n\t\tpublic readonly messageSchema: TMessage,\n\t\tpublic override readonly timeout: number = 30000,\n\t\tpublic override readonly services: TServices = [] as unknown as TServices,\n\t\tpublic override readonly logger: TLogger = DEFAULT_LOGGER as TLogger,\n\t\t/** SQS event-source batch size (deployed). */\n\t\tpublic readonly batchSize?: number,\n\t\t/** Whether the queue is FIFO (deployed). */\n\t\tpublic readonly fifo?: boolean,\n\t\t/**\n\t\t * The construct ids the *worker* `.dependsOn()` named — last, so no\n\t\t * existing positional argument moves.\n\t\t */\n\t\tconstructs: string[] = [],\n\t) {\n\t\tsuper(\n\t\t\tConstructType.Queue,\n\t\t\tlogger,\n\t\t\tservices,\n\t\t\t[],\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\ttimeout,\n\t\t\tundefined, // memorySize\n\t\t\tundefined, // auditorStorageService\n\t\t\tconstructs,\n\t\t);\n\n\t\tthis.id = canonicalId(name);\n\t\tthis.connectionKey = provideKey(this.id, 'publisherConnectionString');\n\t}\n\n\t/**\n\t * What this queue is in the manifest.\n\t *\n\t * A queue is a resource, not a handler: the worker is reached *through* it,\n\t * so the declaration carries the producer's key and nothing about the code\n\t * that drains it. The local target reads this to know which broker has to be\n\t * running and what connection string to inject.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'queue',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.connectionKey],\n\t\t\t\t...(this.fifo ? { fifo: true } : {}),\n\t\t\t\t// Nested rather than a sibling node, because position carries the\n\t\t\t\t// trigger: this handler is reached by messages on this queue and\n\t\t\t\t// by nothing else, so there is no `trigger` field to keep in step.\n\t\t\t\t//\n\t\t\t\t// `handler` is the export name; which directory the build wrote it\n\t\t\t\t// to is the target's business, and a path with a cloud in it does\n\t\t\t\t// not belong in a neutral declaration.\n\t\t\t\tworker: {\n\t\t\t\t\tid: `${this.id}Worker`,\n\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t// Filled by the build from what the worker declared. Empty is a\n\t\t\t\t\t// stated gap, not a claim that it reaches nothing.\n\t\t\t\t\tdependencies: [],\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * The producer side — a `Service` exposing an `EventPublisher` typed to this\n\t * queue's message. Inject it via `.services([queue.publisher])`; the handler\n\t * then calls `services.<name>Publisher.publish([{ type, payload }])`.\n\t *\n\t * It reads `<NAME>_PUBLISHER_CONNECTION_STRING` and builds the transport from\n\t * the URL protocol — `pgboss://` locally, `sqs://` deployed — so the same\n\t * code publishes to Postgres in dev and SQS in prod. Because it's a `Service`,\n\t * `Construct.getEnvironment()` sniffs it, so the env requirement flows into\n\t * the manifest and infra links exactly this queue with least privilege.\n\t */\n\t/**\n\t * The queue as a dependency — what `.dependsOn([emailsQueue])` dissolves\n\t * into, reachable as `services.emails`.\n\t *\n\t * It is the producer: a consumer is the worker written right here, so the\n\t * only thing another construct can want from a queue is the ability to send\n\t * to it. {@link publisher} is the same service under its older\n\t * `<name>Publisher` key, kept for `.services([queue.publisher])`.\n\t */\n\tget service(): Service<\n\t\tUncapitalize<TName>,\n\t\tEventPublisher<QueueMessage<TName, TMessage>>\n\t> {\n\t\tconst { register } = this.publisher;\n\n\t\treturn {\n\t\t\tserviceName: serviceKey(this.id) as Uncapitalize<TName>,\n\t\t\tregister,\n\t\t};\n\t}\n\n\tget publisher(): Service<\n\t\t`${TName}Publisher`,\n\t\tEventPublisher<QueueMessage<TName, TMessage>>\n\t> {\n\t\tconst envVar = this.connectionKey;\n\t\treturn {\n\t\t\tserviceName: `${this.name}Publisher`,\n\t\t\tasync register({ envParser }) {\n\t\t\t\tconst { connectionString } = envParser\n\t\t\t\t\t.create((get) => ({\n\t\t\t\t\t\tconnectionString: get(envVar).string(),\n\t\t\t\t\t}))\n\t\t\t\t\t.parse();\n\n\t\t\t\treturn Publisher.fromConnectionString<QueueMessage<TName, TMessage>>(\n\t\t\t\t\tconnectionString as EventPublisherConnectionString,\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** The context a queue handler receives — a batch of typed messages. */\nexport type QueueContext<\n\tTMessage extends StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> = {\n\tmessages: InferStandardSchema<TMessage>[];\n\tservices: ServiceRecord<TServices>;\n\tlogger: TLogger;\n};\n\nexport type QueueHandler<\n\tTMessage extends StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> = (\n\tctx: QueueContext<TMessage, TServices, TLogger>,\n) => unknown | Promise<unknown>;\n","import type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { cloneWith } from '../clone';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport { Queue, type QueueHandler } from './Queue';\n\n/**\n * Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.\n * Services are an array (sniffed for required env vars); `message` is the typed\n * job payload; `handle` is the single consumer. The queue name is captured as a\n * literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.\n */\nexport class QueueBuilder<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tprivate _name?: string;\n\tprivate _messageSchema?: TMessage;\n\tprivate _timeout = 30000;\n\tprivate _batchSize?: number;\n\tprivate _fifo?: boolean;\n\tprivate _services: TServices = [] as Service[] as TServices;\n\t/** The construct ids `.dependsOn()` named — what the manifest records. */\n\tpublic _constructs: string[] = [];\n\tprivate _logger: TLogger = DEFAULT_LOGGER as TLogger;\n\n\t/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */\n\tqueue<T extends string>(\n\t\tname: T,\n\t): QueueBuilder<T, TMessage, TServices, TLogger> {\n\t\treturn cloneWith(this, { _name: name }) as unknown as QueueBuilder<\n\t\t\tT,\n\t\t\tTMessage,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\ttimeout(timeout: number): this {\n\t\treturn cloneWith(this, { _timeout: timeout });\n\t}\n\n\t/** SQS event-source batch size (deployed). */\n\tbatchSize(batchSize: number): this {\n\t\treturn cloneWith(this, { _batchSize: batchSize });\n\t}\n\n\t/** Mark the queue as FIFO (deployed). */\n\tfifo(fifo = true): this {\n\t\treturn cloneWith(this, { _fifo: fifo });\n\t}\n\n\t/**\n\t * Depend on constructs — a database, a bucket, a mail sender, a queue, a\n\t * topic.\n\t *\n\t * It records the edge and dissolves each construct's client into the\n\t * handler's service record under the construct's own id, so\n\t * `.dependsOn([uploads])` is what makes `services.uploads` exist and type.\n\t *\n\t * Constructs only. A `Service` does not match the shape, which is what keeps\n\t * env sniffing confined to `.services()` and the explicit lift.\n\t */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...ServicesOf<T>], TLogger> {\n\t\t// Both halves of the edge, from one call and one clone: the services the\n\t\t// handler runs with, and the ids the manifest records. Recording them\n\t\t// separately is what let them drift apart.\n\t\t//\n\t\t// `servicesOf` is the half that validates, so it runs first — recording\n\t\t// ids ahead of it left a caught `NotAConstruct` with `undefined` already\n\t\t// on a `string[]`.\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services],\n\t\t\t_constructs: idsOf(constructs, this._constructs),\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...ServicesOf<T>],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tservices<T extends Service[]>(\n\t\tservices: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services] as unknown as TServices,\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...T],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tlogger<T extends Logger>(\n\t\tlogger: T,\n\t): QueueBuilder<TName, TMessage, TServices, T> {\n\t\treturn cloneWith(this, {\n\t\t\t_logger: logger as unknown as TLogger,\n\t\t}) as unknown as QueueBuilder<TName, TMessage, TServices, T>;\n\t}\n\n\t/** The typed message (job) payload the queue carries. */\n\tmessage<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): QueueBuilder<TName, T, TServices, TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_messageSchema: schema as unknown as TMessage,\n\t\t}) as unknown as QueueBuilder<TName, T, TServices, TLogger>;\n\t}\n\n\thandle(\n\t\tfn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>,\n\t): Queue<TName, NonNullable<TMessage>, TServices, TLogger> {\n\t\tif (!this._name) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a name — call .queue(name) before .handle().',\n\t\t\t);\n\t\t}\n\t\tif (!this._messageSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a message schema — call .message(schema) before .handle().',\n\t\t\t);\n\t\t}\n\n\t\tconst queue = new Queue<TName, NonNullable<TMessage>, TServices, TLogger>(\n\t\t\tthis._name as TName,\n\t\t\tfn,\n\t\t\tthis._messageSchema as NonNullable<TMessage>,\n\t\t\tthis._timeout,\n\t\t\tthis._services,\n\t\t\tthis._logger,\n\t\t\tthis._batchSize,\n\t\t\tthis._fifo,\n\t\t\tthis._constructs,\n\t\t);\n\n\t\t// No reset. `.handle()` reads this builder and leaves it alone, so a\n\t\t// configured base — `const fn = f.logger(log).timeout(60_000)` — keeps\n\t\t// its configuration for every construct built from it. The reset that\n\t\t// used to be here wiped the base on first use, which made a base usable\n\t\t// exactly once, and quietly reverted the logger to the default.\n\n\t\treturn queue;\n\t}\n}\n","export {\n\tQueue,\n\ttype QueueContext,\n\ttype QueueHandler,\n\ttype QueueMessage,\n} from './Queue';\n\nimport { QueueBuilder } from './QueueBuilder';\n\nexport { QueueBuilder } from './QueueBuilder';\n\nexport const q = new QueueBuilder();\n"],"mappings":";;;;;;;;;;;;;;;;;AAuCA,IAAa,QAAb,cAKUA,kBAAAA,UAA4D;CA+BpD;CACA;CACA;CACS;CACA;CACA;CAET;CAEA;CAvCjB,eAAe;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,KAAK,UACL,KAAK,WACL,KAAK,SACL,KAAK,YACL,KAAK,OACL,KAAK,WASK;CACZ;AACD;;;ACpJA,MAAa,IAAI,IAAI,aAAa"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["DEFAULT_LOGGER","cloneWith","servicesOf","idsOf","Queue"],"sources":["../../src/queue/QueueBuilder.ts","../../src/queue/index.ts"],"sourcesContent":["import type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { cloneWith } from '../clone';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport { Queue, type QueueHandler } from './Queue';\n\n/**\n * Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.\n * Services are an array (sniffed for required env vars); `message` is the typed\n * job payload; `handle` is the single consumer. The queue name is captured as a\n * literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.\n */\nexport class QueueBuilder<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tprivate _name?: string;\n\tprivate _messageSchema?: TMessage;\n\tprivate _timeout = 30000;\n\tprivate _batchSize?: number;\n\tprivate _fifo?: boolean;\n\tprivate _services: TServices = [] as Service[] as TServices;\n\t/** The construct ids `.dependsOn()` named — what the manifest records. */\n\tpublic _constructs: string[] = [];\n\tprivate _logger: TLogger = DEFAULT_LOGGER as TLogger;\n\n\t/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */\n\tqueue<T extends string>(\n\t\tname: T,\n\t): QueueBuilder<T, TMessage, TServices, TLogger> {\n\t\treturn cloneWith(this, { _name: name }) as unknown as QueueBuilder<\n\t\t\tT,\n\t\t\tTMessage,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\ttimeout(timeout: number): this {\n\t\treturn cloneWith(this, { _timeout: timeout });\n\t}\n\n\t/** SQS event-source batch size (deployed). */\n\tbatchSize(batchSize: number): this {\n\t\treturn cloneWith(this, { _batchSize: batchSize });\n\t}\n\n\t/** Mark the queue as FIFO (deployed). */\n\tfifo(fifo = true): this {\n\t\treturn cloneWith(this, { _fifo: fifo });\n\t}\n\n\t/**\n\t * Depend on constructs — a database, a bucket, a mail sender, a queue, a\n\t * topic.\n\t *\n\t * It records the edge and dissolves each construct's client into the\n\t * handler's service record under the construct's own id, so\n\t * `.dependsOn([uploads])` is what makes `services.uploads` exist and type.\n\t *\n\t * Constructs only. A `Service` does not match the shape, which is what keeps\n\t * env sniffing confined to `.services()` and the explicit lift.\n\t */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...ServicesOf<T>], TLogger> {\n\t\t// Both halves of the edge, from one call and one clone: the services the\n\t\t// handler runs with, and the ids the manifest records. Recording them\n\t\t// separately is what let them drift apart.\n\t\t//\n\t\t// `servicesOf` is the half that validates, so it runs first — recording\n\t\t// ids ahead of it left a caught `NotAConstruct` with `undefined` already\n\t\t// on a `string[]`.\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services],\n\t\t\t_constructs: idsOf(constructs, this._constructs),\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...ServicesOf<T>],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tservices<T extends Service[]>(\n\t\tservices: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services] as unknown as TServices,\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...T],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tlogger<T extends Logger>(\n\t\tlogger: T,\n\t): QueueBuilder<TName, TMessage, TServices, T> {\n\t\treturn cloneWith(this, {\n\t\t\t_logger: logger as unknown as TLogger,\n\t\t}) as unknown as QueueBuilder<TName, TMessage, TServices, T>;\n\t}\n\n\t/** The typed message (job) payload the queue carries. */\n\tmessage<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): QueueBuilder<TName, T, TServices, TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_messageSchema: schema as unknown as TMessage,\n\t\t}) as unknown as QueueBuilder<TName, T, TServices, TLogger>;\n\t}\n\n\thandle(\n\t\tfn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>,\n\t): Queue<TName, NonNullable<TMessage>, TServices, TLogger> {\n\t\tif (!this._name) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a name — call .queue(name) before .handle().',\n\t\t\t);\n\t\t}\n\t\tif (!this._messageSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a message schema — call .message(schema) before .handle().',\n\t\t\t);\n\t\t}\n\n\t\tconst queue = new Queue<TName, NonNullable<TMessage>, TServices, TLogger>(\n\t\t\tthis._name as TName,\n\t\t\tfn,\n\t\t\tthis._messageSchema as NonNullable<TMessage>,\n\t\t\tthis._timeout,\n\t\t\tthis._services,\n\t\t\tthis._logger,\n\t\t\tthis._batchSize,\n\t\t\tthis._fifo,\n\t\t\tthis._constructs,\n\t\t);\n\n\t\t// No reset. `.handle()` reads this builder and leaves it alone, so a\n\t\t// configured base — `const fn = f.logger(log).timeout(60_000)` — keeps\n\t\t// its configuration for every construct built from it. The reset that\n\t\t// used to be here wiped the base on first use, which made a base usable\n\t\t// exactly once, and quietly reverted the logger to the default.\n\n\t\treturn queue;\n\t}\n}\n","export {\n\tQueue,\n\ttype QueueContext,\n\ttype QueueHandler,\n\ttype QueueMessage,\n} from './Queue';\n\nimport { QueueBuilder } from './QueueBuilder';\n\nexport { QueueBuilder } from './QueueBuilder';\n\nexport const q = new QueueBuilder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KAAK,WASK;CACZ;AACD;;;ACpJA,MAAa,IAAI,IAAI,aAAa"}
|
package/dist/queue/index.mjs
CHANGED
|
@@ -1,120 +1,7 @@
|
|
|
1
|
-
import { t as Construct } from "../Construct-Detz65RA.mjs";
|
|
2
1
|
import { idsOf, servicesOf } from "../construct-interface.mjs";
|
|
3
2
|
import { t as cloneWith } from "../clone-EKNovYHu.mjs";
|
|
4
|
-
import {
|
|
3
|
+
import { t as Queue } from "../Queue-Dfumm1WR.mjs";
|
|
5
4
|
import { DEFAULT_LOGGER } from "@geekmidas/logger/console";
|
|
6
|
-
import { Publisher } from "@geekmidas/events";
|
|
7
|
-
//#region src/queue/Queue.ts
|
|
8
|
-
/**
|
|
9
|
-
* A queue worker — a point-to-point SQS-style queue and its single consumer.
|
|
10
|
-
* Unlike a `Subscriber` (topic fan-out, filtered by `subscribedEvents`), a queue
|
|
11
|
-
* drains every message of its one `message` type. Build one with `q` (see
|
|
12
|
-
* `QueueBuilder`); `gkm build` discovers it into the manifest's `queues` field.
|
|
13
|
-
*
|
|
14
|
-
* The producer side is {@link Queue.publisher} — a ready-to-inject `Service`
|
|
15
|
-
* that any endpoint/function drops into `.services([...])` to send messages.
|
|
16
|
-
*/
|
|
17
|
-
var Queue = class extends Construct {
|
|
18
|
-
name;
|
|
19
|
-
handler;
|
|
20
|
-
messageSchema;
|
|
21
|
-
timeout;
|
|
22
|
-
services;
|
|
23
|
-
logger;
|
|
24
|
-
batchSize;
|
|
25
|
-
fifo;
|
|
26
|
-
__IS_QUEUE__ = true;
|
|
27
|
-
static isQueue(obj) {
|
|
28
|
-
return Boolean(obj && obj.__IS_QUEUE__ === true && obj.type === "dev.geekmidas.function.queue");
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* The canonical id this queue is declared under.
|
|
32
|
-
*
|
|
33
|
-
* Derived from the name rather than given separately, so `emails` and
|
|
34
|
-
* `Emails` are one queue. The name stays what it was: it is the wire `type`
|
|
35
|
-
* a producer sends and the worker subscribes to, and changing that would
|
|
36
|
-
* silently orphan in-flight messages.
|
|
37
|
-
*/
|
|
38
|
-
id;
|
|
39
|
-
/**
|
|
40
|
-
* The producer's env key. Read by both {@link declare} and
|
|
41
|
-
* {@link publisher}, so what the target publishes and what the producer
|
|
42
|
-
* looks up cannot drift.
|
|
43
|
-
*/
|
|
44
|
-
connectionKey;
|
|
45
|
-
constructor(name, handler, messageSchema, timeout = 3e4, services = [], logger = DEFAULT_LOGGER, batchSize, fifo, constructs = []) {
|
|
46
|
-
super("dev.geekmidas.function.queue", logger, services, [], void 0, void 0, timeout, void 0, void 0, constructs);
|
|
47
|
-
this.name = name;
|
|
48
|
-
this.handler = handler;
|
|
49
|
-
this.messageSchema = messageSchema;
|
|
50
|
-
this.timeout = timeout;
|
|
51
|
-
this.services = services;
|
|
52
|
-
this.logger = logger;
|
|
53
|
-
this.batchSize = batchSize;
|
|
54
|
-
this.fifo = fifo;
|
|
55
|
-
this.id = canonicalId(name);
|
|
56
|
-
this.connectionKey = provideKey(this.id, "publisherConnectionString");
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* What this queue is in the manifest.
|
|
60
|
-
*
|
|
61
|
-
* A queue is a resource, not a handler: the worker is reached *through* it,
|
|
62
|
-
* so the declaration carries the producer's key and nothing about the code
|
|
63
|
-
* that drains it. The local target reads this to know which broker has to be
|
|
64
|
-
* running and what connection string to inject.
|
|
65
|
-
*/
|
|
66
|
-
declare() {
|
|
67
|
-
return [{
|
|
68
|
-
kind: "queue",
|
|
69
|
-
id: this.id,
|
|
70
|
-
provides: [this.connectionKey],
|
|
71
|
-
...this.fifo ? { fifo: true } : {},
|
|
72
|
-
worker: {
|
|
73
|
-
id: `${this.id}Worker`,
|
|
74
|
-
handler: `${this.id}.handler`,
|
|
75
|
-
dependencies: []
|
|
76
|
-
}
|
|
77
|
-
}];
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* The producer side — a `Service` exposing an `EventPublisher` typed to this
|
|
81
|
-
* queue's message. Inject it via `.services([queue.publisher])`; the handler
|
|
82
|
-
* then calls `services.<name>Publisher.publish([{ type, payload }])`.
|
|
83
|
-
*
|
|
84
|
-
* It reads `<NAME>_PUBLISHER_CONNECTION_STRING` and builds the transport from
|
|
85
|
-
* the URL protocol — `pgboss://` locally, `sqs://` deployed — so the same
|
|
86
|
-
* code publishes to Postgres in dev and SQS in prod. Because it's a `Service`,
|
|
87
|
-
* `Construct.getEnvironment()` sniffs it, so the env requirement flows into
|
|
88
|
-
* the manifest and infra links exactly this queue with least privilege.
|
|
89
|
-
*/
|
|
90
|
-
/**
|
|
91
|
-
* The queue as a dependency — what `.dependsOn([emailsQueue])` dissolves
|
|
92
|
-
* into, reachable as `services.emails`.
|
|
93
|
-
*
|
|
94
|
-
* It is the producer: a consumer is the worker written right here, so the
|
|
95
|
-
* only thing another construct can want from a queue is the ability to send
|
|
96
|
-
* to it. {@link publisher} is the same service under its older
|
|
97
|
-
* `<name>Publisher` key, kept for `.services([queue.publisher])`.
|
|
98
|
-
*/
|
|
99
|
-
get service() {
|
|
100
|
-
const { register } = this.publisher;
|
|
101
|
-
return {
|
|
102
|
-
serviceName: serviceKey(this.id),
|
|
103
|
-
register
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
get publisher() {
|
|
107
|
-
const envVar = this.connectionKey;
|
|
108
|
-
return {
|
|
109
|
-
serviceName: `${this.name}Publisher`,
|
|
110
|
-
async register({ envParser }) {
|
|
111
|
-
const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
|
|
112
|
-
return Publisher.fromConnectionString(connectionString);
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
//#endregion
|
|
118
5
|
//#region src/queue/QueueBuilder.ts
|
|
119
6
|
/**
|
|
120
7
|
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
package/dist/queue/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/queue/Queue.ts","../../src/queue/QueueBuilder.ts","../../src/queue/index.ts"],"sourcesContent":["import {\n\ttype EventPublisher,\n\ttype EventPublisherConnectionString,\n\ttype PublishableMessage,\n\tPublisher,\n} from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Construct, ConstructType } from '../Construct';\n\n/**\n * The wire message a queue carries: `{ type: <queue name>, payload: <message> }`.\n * The producer publishes this shape and the worker receives the `payload`s as\n * its `messages`. Typing `type` to the queue name keeps the publisher fully\n * typed and lets pg-boss (local) / SQS (deployed) route by name.\n */\nexport type QueueMessage<\n\tTName extends string,\n\tTMessage extends StandardSchemaV1,\n> = PublishableMessage<TName, InferStandardSchema<TMessage>>;\n\n/**\n * A queue worker — a point-to-point SQS-style queue and its single consumer.\n * Unlike a `Subscriber` (topic fan-out, filtered by `subscribedEvents`), a queue\n * drains every message of its one `message` type. Build one with `q` (see\n * `QueueBuilder`); `gkm build` discovers it into the manifest's `queues` field.\n *\n * The producer side is {@link Queue.publisher} — a ready-to-inject `Service`\n * that any endpoint/function drops into `.services([...])` to send messages.\n */\nexport class Queue<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 = StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> extends Construct<TLogger, string, undefined, undefined, TServices> {\n\t__IS_QUEUE__ = true;\n\n\tstatic isQueue(\n\t\tobj: unknown,\n\t): obj is Queue<string, StandardSchemaV1, Service[], Logger> {\n\t\treturn Boolean(\n\t\t\tobj &&\n\t\t\t\t(obj as { __IS_QUEUE__?: boolean }).__IS_QUEUE__ === true &&\n\t\t\t\t(obj as Construct).type === ConstructType.Queue,\n\t\t);\n\t}\n\n\t/**\n\t * The canonical id this queue is declared under.\n\t *\n\t * Derived from the name rather than given separately, so `emails` and\n\t * `Emails` are one queue. The name stays what it was: it is the wire `type`\n\t * a producer sends and the worker subscribes to, and changing that would\n\t * silently orphan in-flight messages.\n\t */\n\treadonly id: string;\n\n\t/**\n\t * The producer's env key. Read by both {@link declare} and\n\t * {@link publisher}, so what the target publishes and what the producer\n\t * looks up cannot drift.\n\t */\n\tprivate readonly connectionKey: string;\n\n\tconstructor(\n\t\tpublic readonly name: TName,\n\t\tpublic readonly handler: QueueHandler<TMessage, TServices, TLogger>,\n\t\tpublic readonly messageSchema: TMessage,\n\t\tpublic override readonly timeout: number = 30000,\n\t\tpublic override readonly services: TServices = [] as unknown as TServices,\n\t\tpublic override readonly logger: TLogger = DEFAULT_LOGGER as TLogger,\n\t\t/** SQS event-source batch size (deployed). */\n\t\tpublic readonly batchSize?: number,\n\t\t/** Whether the queue is FIFO (deployed). */\n\t\tpublic readonly fifo?: boolean,\n\t\t/**\n\t\t * The construct ids the *worker* `.dependsOn()` named — last, so no\n\t\t * existing positional argument moves.\n\t\t */\n\t\tconstructs: string[] = [],\n\t) {\n\t\tsuper(\n\t\t\tConstructType.Queue,\n\t\t\tlogger,\n\t\t\tservices,\n\t\t\t[],\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\ttimeout,\n\t\t\tundefined, // memorySize\n\t\t\tundefined, // auditorStorageService\n\t\t\tconstructs,\n\t\t);\n\n\t\tthis.id = canonicalId(name);\n\t\tthis.connectionKey = provideKey(this.id, 'publisherConnectionString');\n\t}\n\n\t/**\n\t * What this queue is in the manifest.\n\t *\n\t * A queue is a resource, not a handler: the worker is reached *through* it,\n\t * so the declaration carries the producer's key and nothing about the code\n\t * that drains it. The local target reads this to know which broker has to be\n\t * running and what connection string to inject.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'queue',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.connectionKey],\n\t\t\t\t...(this.fifo ? { fifo: true } : {}),\n\t\t\t\t// Nested rather than a sibling node, because position carries the\n\t\t\t\t// trigger: this handler is reached by messages on this queue and\n\t\t\t\t// by nothing else, so there is no `trigger` field to keep in step.\n\t\t\t\t//\n\t\t\t\t// `handler` is the export name; which directory the build wrote it\n\t\t\t\t// to is the target's business, and a path with a cloud in it does\n\t\t\t\t// not belong in a neutral declaration.\n\t\t\t\tworker: {\n\t\t\t\t\tid: `${this.id}Worker`,\n\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t// Filled by the build from what the worker declared. Empty is a\n\t\t\t\t\t// stated gap, not a claim that it reaches nothing.\n\t\t\t\t\tdependencies: [],\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * The producer side — a `Service` exposing an `EventPublisher` typed to this\n\t * queue's message. Inject it via `.services([queue.publisher])`; the handler\n\t * then calls `services.<name>Publisher.publish([{ type, payload }])`.\n\t *\n\t * It reads `<NAME>_PUBLISHER_CONNECTION_STRING` and builds the transport from\n\t * the URL protocol — `pgboss://` locally, `sqs://` deployed — so the same\n\t * code publishes to Postgres in dev and SQS in prod. Because it's a `Service`,\n\t * `Construct.getEnvironment()` sniffs it, so the env requirement flows into\n\t * the manifest and infra links exactly this queue with least privilege.\n\t */\n\t/**\n\t * The queue as a dependency — what `.dependsOn([emailsQueue])` dissolves\n\t * into, reachable as `services.emails`.\n\t *\n\t * It is the producer: a consumer is the worker written right here, so the\n\t * only thing another construct can want from a queue is the ability to send\n\t * to it. {@link publisher} is the same service under its older\n\t * `<name>Publisher` key, kept for `.services([queue.publisher])`.\n\t */\n\tget service(): Service<\n\t\tUncapitalize<TName>,\n\t\tEventPublisher<QueueMessage<TName, TMessage>>\n\t> {\n\t\tconst { register } = this.publisher;\n\n\t\treturn {\n\t\t\tserviceName: serviceKey(this.id) as Uncapitalize<TName>,\n\t\t\tregister,\n\t\t};\n\t}\n\n\tget publisher(): Service<\n\t\t`${TName}Publisher`,\n\t\tEventPublisher<QueueMessage<TName, TMessage>>\n\t> {\n\t\tconst envVar = this.connectionKey;\n\t\treturn {\n\t\t\tserviceName: `${this.name}Publisher`,\n\t\t\tasync register({ envParser }) {\n\t\t\t\tconst { connectionString } = envParser\n\t\t\t\t\t.create((get) => ({\n\t\t\t\t\t\tconnectionString: get(envVar).string(),\n\t\t\t\t\t}))\n\t\t\t\t\t.parse();\n\n\t\t\t\treturn Publisher.fromConnectionString<QueueMessage<TName, TMessage>>(\n\t\t\t\t\tconnectionString as EventPublisherConnectionString,\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** The context a queue handler receives — a batch of typed messages. */\nexport type QueueContext<\n\tTMessage extends StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> = {\n\tmessages: InferStandardSchema<TMessage>[];\n\tservices: ServiceRecord<TServices>;\n\tlogger: TLogger;\n};\n\nexport type QueueHandler<\n\tTMessage extends StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> = (\n\tctx: QueueContext<TMessage, TServices, TLogger>,\n) => unknown | Promise<unknown>;\n","import type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { cloneWith } from '../clone';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport { Queue, type QueueHandler } from './Queue';\n\n/**\n * Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.\n * Services are an array (sniffed for required env vars); `message` is the typed\n * job payload; `handle` is the single consumer. The queue name is captured as a\n * literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.\n */\nexport class QueueBuilder<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tprivate _name?: string;\n\tprivate _messageSchema?: TMessage;\n\tprivate _timeout = 30000;\n\tprivate _batchSize?: number;\n\tprivate _fifo?: boolean;\n\tprivate _services: TServices = [] as Service[] as TServices;\n\t/** The construct ids `.dependsOn()` named — what the manifest records. */\n\tpublic _constructs: string[] = [];\n\tprivate _logger: TLogger = DEFAULT_LOGGER as TLogger;\n\n\t/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */\n\tqueue<T extends string>(\n\t\tname: T,\n\t): QueueBuilder<T, TMessage, TServices, TLogger> {\n\t\treturn cloneWith(this, { _name: name }) as unknown as QueueBuilder<\n\t\t\tT,\n\t\t\tTMessage,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\ttimeout(timeout: number): this {\n\t\treturn cloneWith(this, { _timeout: timeout });\n\t}\n\n\t/** SQS event-source batch size (deployed). */\n\tbatchSize(batchSize: number): this {\n\t\treturn cloneWith(this, { _batchSize: batchSize });\n\t}\n\n\t/** Mark the queue as FIFO (deployed). */\n\tfifo(fifo = true): this {\n\t\treturn cloneWith(this, { _fifo: fifo });\n\t}\n\n\t/**\n\t * Depend on constructs — a database, a bucket, a mail sender, a queue, a\n\t * topic.\n\t *\n\t * It records the edge and dissolves each construct's client into the\n\t * handler's service record under the construct's own id, so\n\t * `.dependsOn([uploads])` is what makes `services.uploads` exist and type.\n\t *\n\t * Constructs only. A `Service` does not match the shape, which is what keeps\n\t * env sniffing confined to `.services()` and the explicit lift.\n\t */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...ServicesOf<T>], TLogger> {\n\t\t// Both halves of the edge, from one call and one clone: the services the\n\t\t// handler runs with, and the ids the manifest records. Recording them\n\t\t// separately is what let them drift apart.\n\t\t//\n\t\t// `servicesOf` is the half that validates, so it runs first — recording\n\t\t// ids ahead of it left a caught `NotAConstruct` with `undefined` already\n\t\t// on a `string[]`.\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services],\n\t\t\t_constructs: idsOf(constructs, this._constructs),\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...ServicesOf<T>],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tservices<T extends Service[]>(\n\t\tservices: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services] as unknown as TServices,\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...T],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tlogger<T extends Logger>(\n\t\tlogger: T,\n\t): QueueBuilder<TName, TMessage, TServices, T> {\n\t\treturn cloneWith(this, {\n\t\t\t_logger: logger as unknown as TLogger,\n\t\t}) as unknown as QueueBuilder<TName, TMessage, TServices, T>;\n\t}\n\n\t/** The typed message (job) payload the queue carries. */\n\tmessage<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): QueueBuilder<TName, T, TServices, TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_messageSchema: schema as unknown as TMessage,\n\t\t}) as unknown as QueueBuilder<TName, T, TServices, TLogger>;\n\t}\n\n\thandle(\n\t\tfn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>,\n\t): Queue<TName, NonNullable<TMessage>, TServices, TLogger> {\n\t\tif (!this._name) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a name — call .queue(name) before .handle().',\n\t\t\t);\n\t\t}\n\t\tif (!this._messageSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a message schema — call .message(schema) before .handle().',\n\t\t\t);\n\t\t}\n\n\t\tconst queue = new Queue<TName, NonNullable<TMessage>, TServices, TLogger>(\n\t\t\tthis._name as TName,\n\t\t\tfn,\n\t\t\tthis._messageSchema as NonNullable<TMessage>,\n\t\t\tthis._timeout,\n\t\t\tthis._services,\n\t\t\tthis._logger,\n\t\t\tthis._batchSize,\n\t\t\tthis._fifo,\n\t\t\tthis._constructs,\n\t\t);\n\n\t\t// No reset. `.handle()` reads this builder and leaves it alone, so a\n\t\t// configured base — `const fn = f.logger(log).timeout(60_000)` — keeps\n\t\t// its configuration for every construct built from it. The reset that\n\t\t// used to be here wiped the base on first use, which made a base usable\n\t\t// exactly once, and quietly reverted the logger to the default.\n\n\t\treturn queue;\n\t}\n}\n","export {\n\tQueue,\n\ttype QueueContext,\n\ttype QueueHandler,\n\ttype QueueMessage,\n} from './Queue';\n\nimport { QueueBuilder } from './QueueBuilder';\n\nexport { QueueBuilder } from './QueueBuilder';\n\nexport const q = new QueueBuilder();\n"],"mappings":";;;;;;;;;;;;;;;;AAuCA,IAAa,QAAb,cAKU,UAA4D;CA+BpD;CACA;CACA;CACS;CACA;CACA;CAET;CAEA;CAvCjB,eAAe;CAEf,OAAO,QACN,KAC4D;EAC5D,OAAO,QACN,OACE,IAAmC,iBAAiB,QACpD,IAAkB,SAAA,8BACrB;CACD;;;;;;;;;CAUA;;;;;;CAOA;CAEA,YACC,MACA,SACA,eACA,UAA2C,KAC3C,WAA+C,CAAC,GAChD,SAA2C,gBAE3C,WAEA,MAKA,aAAuB,CAAC,GACvB;EACD,MAAA,gCAEC,QACA,UACA,CAAC,GACD,KAAA,GACA,KAAA,GACA,SACA,KAAA,GACA,KAAA,GACA,UACD;EA3BgB,KAAA,OAAA;EACA,KAAA,UAAA;EACA,KAAA,gBAAA;EACS,KAAA,UAAA;EACA,KAAA,WAAA;EACA,KAAA,SAAA;EAET,KAAA,YAAA;EAEA,KAAA,OAAA;EAoBhB,KAAK,KAAK,YAAY,IAAI;EAC1B,KAAK,gBAAgB,WAAW,KAAK,IAAI,2BAA2B;CACrE;;;;;;;;;CAUA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C1C,aAAa,MAAM,YAAY,KAAK,WAAW;EAChD,CAAC;CAMF;CAEA,SACC,UAC+D;EAC/D,OAAO,UAAU,MAAM,EACtB,WAAW,CAAC,GAAG,KAAK,WAAW,GAAG,QAAQ,EAC3C,CAAC;CAMF;CAEA,OACC,QAC8C;EAC9C,OAAO,UAAU,MAAM,EACtB,SAAS,OACV,CAAC;CACF;;CAGA,QACC,QAC6C;EAC7C,OAAO,UAAU,MAAM,EACtB,gBAAgB,OACjB,CAAC;CACF;CAEA,OACC,IAC0D;EAC1D,IAAI,CAAC,KAAK,OACT,MAAM,IAAI,MACT,6DACD;EAED,IAAI,CAAC,KAAK,gBACT,MAAM,IAAI,MACT,2EACD;EAqBD,OAAO,IAlBW,MACjB,KAAK,OACL,IACA,KAAK,gBACL,KAAK,UACL,KAAK,WACL,KAAK,SACL,KAAK,YACL,KAAK,OACL,KAAK,WASK;CACZ;AACD;;;ACpJA,MAAa,IAAI,IAAI,aAAa"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/queue/QueueBuilder.ts","../../src/queue/index.ts"],"sourcesContent":["import type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { cloneWith } from '../clone';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport { Queue, type QueueHandler } from './Queue';\n\n/**\n * Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.\n * Services are an array (sniffed for required env vars); `message` is the typed\n * job payload; `handle` is the single consumer. The queue name is captured as a\n * literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.\n */\nexport class QueueBuilder<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tprivate _name?: string;\n\tprivate _messageSchema?: TMessage;\n\tprivate _timeout = 30000;\n\tprivate _batchSize?: number;\n\tprivate _fifo?: boolean;\n\tprivate _services: TServices = [] as Service[] as TServices;\n\t/** The construct ids `.dependsOn()` named — what the manifest records. */\n\tpublic _constructs: string[] = [];\n\tprivate _logger: TLogger = DEFAULT_LOGGER as TLogger;\n\n\t/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */\n\tqueue<T extends string>(\n\t\tname: T,\n\t): QueueBuilder<T, TMessage, TServices, TLogger> {\n\t\treturn cloneWith(this, { _name: name }) as unknown as QueueBuilder<\n\t\t\tT,\n\t\t\tTMessage,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\ttimeout(timeout: number): this {\n\t\treturn cloneWith(this, { _timeout: timeout });\n\t}\n\n\t/** SQS event-source batch size (deployed). */\n\tbatchSize(batchSize: number): this {\n\t\treturn cloneWith(this, { _batchSize: batchSize });\n\t}\n\n\t/** Mark the queue as FIFO (deployed). */\n\tfifo(fifo = true): this {\n\t\treturn cloneWith(this, { _fifo: fifo });\n\t}\n\n\t/**\n\t * Depend on constructs — a database, a bucket, a mail sender, a queue, a\n\t * topic.\n\t *\n\t * It records the edge and dissolves each construct's client into the\n\t * handler's service record under the construct's own id, so\n\t * `.dependsOn([uploads])` is what makes `services.uploads` exist and type.\n\t *\n\t * Constructs only. A `Service` does not match the shape, which is what keeps\n\t * env sniffing confined to `.services()` and the explicit lift.\n\t */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...ServicesOf<T>], TLogger> {\n\t\t// Both halves of the edge, from one call and one clone: the services the\n\t\t// handler runs with, and the ids the manifest records. Recording them\n\t\t// separately is what let them drift apart.\n\t\t//\n\t\t// `servicesOf` is the half that validates, so it runs first — recording\n\t\t// ids ahead of it left a caught `NotAConstruct` with `undefined` already\n\t\t// on a `string[]`.\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services],\n\t\t\t_constructs: idsOf(constructs, this._constructs),\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...ServicesOf<T>],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tservices<T extends Service[]>(\n\t\tservices: T,\n\t): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_services: [...this._services, ...services] as unknown as TServices,\n\t\t}) as unknown as QueueBuilder<\n\t\t\tTName,\n\t\t\tTMessage,\n\t\t\t[...TServices, ...T],\n\t\t\tTLogger\n\t\t>;\n\t}\n\n\tlogger<T extends Logger>(\n\t\tlogger: T,\n\t): QueueBuilder<TName, TMessage, TServices, T> {\n\t\treturn cloneWith(this, {\n\t\t\t_logger: logger as unknown as TLogger,\n\t\t}) as unknown as QueueBuilder<TName, TMessage, TServices, T>;\n\t}\n\n\t/** The typed message (job) payload the queue carries. */\n\tmessage<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): QueueBuilder<TName, T, TServices, TLogger> {\n\t\treturn cloneWith(this, {\n\t\t\t_messageSchema: schema as unknown as TMessage,\n\t\t}) as unknown as QueueBuilder<TName, T, TServices, TLogger>;\n\t}\n\n\thandle(\n\t\tfn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>,\n\t): Queue<TName, NonNullable<TMessage>, TServices, TLogger> {\n\t\tif (!this._name) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a name — call .queue(name) before .handle().',\n\t\t\t);\n\t\t}\n\t\tif (!this._messageSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t'Queue requires a message schema — call .message(schema) before .handle().',\n\t\t\t);\n\t\t}\n\n\t\tconst queue = new Queue<TName, NonNullable<TMessage>, TServices, TLogger>(\n\t\t\tthis._name as TName,\n\t\t\tfn,\n\t\t\tthis._messageSchema as NonNullable<TMessage>,\n\t\t\tthis._timeout,\n\t\t\tthis._services,\n\t\t\tthis._logger,\n\t\t\tthis._batchSize,\n\t\t\tthis._fifo,\n\t\t\tthis._constructs,\n\t\t);\n\n\t\t// No reset. `.handle()` reads this builder and leaves it alone, so a\n\t\t// configured base — `const fn = f.logger(log).timeout(60_000)` — keeps\n\t\t// its configuration for every construct built from it. The reset that\n\t\t// used to be here wiped the base on first use, which made a base usable\n\t\t// exactly once, and quietly reverted the logger to the default.\n\n\t\treturn queue;\n\t}\n}\n","export {\n\tQueue,\n\ttype QueueContext,\n\ttype QueueHandler,\n\ttype QueueMessage,\n} from './Queue';\n\nimport { QueueBuilder } from './QueueBuilder';\n\nexport { QueueBuilder } from './QueueBuilder';\n\nexport const q = new QueueBuilder();\n"],"mappings":";;;;;;;;;;;AAmBA,IAAa,eAAb,MAKE;CACD;CACA;CACA,WAAmB;CACnB;CACA;CACA,YAA+B,CAAC;;CAEhC,cAA+B,CAAC;CAChC,UAA2B;;CAG3B,MACC,MACgD;EAChD,OAAO,UAAU,MAAM,EAAE,OAAO,KAAK,CAAC;CAMvC;CAEA,QAAQ,SAAuB;EAC9B,OAAO,UAAU,MAAM,EAAE,UAAU,QAAQ,CAAC;CAC7C;;CAGA,UAAU,WAAyB;EAClC,OAAO,UAAU,MAAM,EAAE,YAAY,UAAU,CAAC;CACjD;;CAGA,KAAK,OAAO,MAAY;EACvB,OAAO,UAAU,MAAM,EAAE,OAAO,KAAK,CAAC;CACvC;;;;;;;;;;;;CAaA,UACC,YAC2E;EAQ3E,MAAM,WAAW,WAAW,UAAU;EAEtC,OAAO,UAAU,MAAM;GACtB,WAAW,CAAC,GAAG,KAAK,WAAW,GAAG,QAAQ;GAC1C,aAAa,MAAM,YAAY,KAAK,WAAW;EAChD,CAAC;CAMF;CAEA,SACC,UAC+D;EAC/D,OAAO,UAAU,MAAM,EACtB,WAAW,CAAC,GAAG,KAAK,WAAW,GAAG,QAAQ,EAC3C,CAAC;CAMF;CAEA,OACC,QAC8C;EAC9C,OAAO,UAAU,MAAM,EACtB,SAAS,OACV,CAAC;CACF;;CAGA,QACC,QAC6C;EAC7C,OAAO,UAAU,MAAM,EACtB,gBAAgB,OACjB,CAAC;CACF;CAEA,OACC,IAC0D;EAC1D,IAAI,CAAC,KAAK,OACT,MAAM,IAAI,MACT,6DACD;EAED,IAAI,CAAC,KAAK,gBACT,MAAM,IAAI,MACT,2EACD;EAqBD,OAAO,IAlBW,MACjB,KAAK,OACL,IACA,KAAK,gBACL,KAAK,UACL,KAAK,WACL,KAAK,SACL,KAAK,YACL,KAAK,OACL,KAAK,WASK;CACZ;AACD;;;ACpJA,MAAa,IAAI,IAAI,aAAa"}
|
package/dist/rest-api.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as Declarable, t as Authenticator } from "./construct-interface-DIaTNKax.cjs";
|
|
2
|
-
import { T as BuiltInSecuritySchemeId } from "./Endpoint-
|
|
3
|
-
import { t as EndpointFactory } from "./EndpointFactory-
|
|
2
|
+
import { T as BuiltInSecuritySchemeId } from "./Endpoint-CrhoafsT.cjs";
|
|
3
|
+
import { t as EndpointFactory } from "./EndpointFactory-CiCzFdMx.cjs";
|
|
4
4
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
5
5
|
import { Logger } from "@geekmidas/logger";
|
|
6
6
|
import { ConstructName, Declaration, Dependency } from "@geekmidas/manifest";
|
package/dist/rest-api.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as Declarable, t as Authenticator } from "./construct-interface-Clz7_BwB.mjs";
|
|
2
|
-
import { T as BuiltInSecuritySchemeId } from "./Endpoint-
|
|
3
|
-
import { t as EndpointFactory } from "./EndpointFactory-
|
|
2
|
+
import { T as BuiltInSecuritySchemeId } from "./Endpoint-pTZrMs_h.mjs";
|
|
3
|
+
import { t as EndpointFactory } from "./EndpointFactory-BSLH4hSU.mjs";
|
|
4
4
|
import { ConstructName, Declaration, Dependency } from "@geekmidas/manifest";
|
|
5
5
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
6
6
|
import { Logger } from "@geekmidas/logger";
|