@cicord/client 0.1.6 → 0.1.8
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/LICENSE +1 -1
- package/dist/index.d.mts +86 -6
- package/dist/index.mjs +24 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -187,7 +187,7 @@
|
|
|
187
187
|
same "printed page" as the copyright notice for easier
|
|
188
188
|
identification within third-party archives.
|
|
189
189
|
|
|
190
|
-
Copyright
|
|
190
|
+
Copyright 2026 Cicord team
|
|
191
191
|
|
|
192
192
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
193
|
you may not use this file except in compliance with the License.
|
package/dist/index.d.mts
CHANGED
|
@@ -246,6 +246,41 @@ interface ServerStatus {
|
|
|
246
246
|
features?: string[];
|
|
247
247
|
/** The `COMMUNITY` feature is enabled. */
|
|
248
248
|
community?: boolean;
|
|
249
|
+
/**
|
|
250
|
+
* Set while enforcement is paused on the server (emergency switch): nothing is applied
|
|
251
|
+
* to it. `sync` still reports the drift from git.
|
|
252
|
+
*/
|
|
253
|
+
paused?: PauseInfo;
|
|
254
|
+
}
|
|
255
|
+
/** Who paused enforcement on a server, when and why. */
|
|
256
|
+
interface PauseInfo {
|
|
257
|
+
/** Actor: `discord:<user id>` or `runtime-token`. */
|
|
258
|
+
by: string;
|
|
259
|
+
/** Display name of the Discord user, when known. */
|
|
260
|
+
byName?: string;
|
|
261
|
+
at: Timestamp;
|
|
262
|
+
reason?: string;
|
|
263
|
+
}
|
|
264
|
+
/** `GET /servers/{server}/pause`: the pause, and the plan that resuming lets apply. */
|
|
265
|
+
interface PauseState {
|
|
266
|
+
/** `null` when the server is not paused. */
|
|
267
|
+
paused: PauseInfo | null;
|
|
268
|
+
/** The pending plan; `null` when it cannot be computed (`planError` says why). */
|
|
269
|
+
plan: Plan | null;
|
|
270
|
+
planError?: string;
|
|
271
|
+
}
|
|
272
|
+
/** `POST /servers/{server}/pause`. */
|
|
273
|
+
interface PauseResult {
|
|
274
|
+
paused: PauseInfo;
|
|
275
|
+
/** `false` when the server was already paused (nothing changed). */
|
|
276
|
+
changed: boolean;
|
|
277
|
+
}
|
|
278
|
+
/** `POST /servers/{server}/resume`. */
|
|
279
|
+
interface ResumeResult {
|
|
280
|
+
/** `false` when the server was not paused. */
|
|
281
|
+
resumed: boolean;
|
|
282
|
+
/** The pause that ended. */
|
|
283
|
+
pause?: PauseInfo;
|
|
249
284
|
}
|
|
250
285
|
/** Server images editable from the admin UI (`PUT /servers/{server}/assets/{kind}`). */
|
|
251
286
|
type ServerAssetKind = "icon" | "banner" | "splash";
|
|
@@ -255,9 +290,9 @@ interface ServerAssetResult {
|
|
|
255
290
|
mode: "commit" | "pullRequest" | (string & {});
|
|
256
291
|
revision: string;
|
|
257
292
|
pullRequestUrl: string;
|
|
258
|
-
/** Repository path of the written file, e.g. `servers/assets/
|
|
293
|
+
/** Repository path of the written file, e.g. `servers/assets/my-community-icon.png`. */
|
|
259
294
|
path: string;
|
|
260
|
-
/** Value set in `spec.profile.<kind>`, e.g. `./assets/
|
|
295
|
+
/** Value set in `spec.profile.<kind>`, e.g. `./assets/my-community-icon.png`. */
|
|
261
296
|
value: string;
|
|
262
297
|
format: "png" | "jpeg" | "gif" | "webp" | (string & {});
|
|
263
298
|
width: number;
|
|
@@ -297,7 +332,11 @@ interface RuntimeStatus {
|
|
|
297
332
|
servers: ServerStatus[];
|
|
298
333
|
bots: BotStatus[];
|
|
299
334
|
}
|
|
300
|
-
|
|
335
|
+
/**
|
|
336
|
+
* `paused` / `resumed`: enforcement was paused / resumed on the server; `skipped`: a
|
|
337
|
+
* revision was not applied to a paused server.
|
|
338
|
+
*/
|
|
339
|
+
type SyncRecordStatus = "succeeded" | "failed" | "rejected" | "paused" | "resumed" | "skipped";
|
|
301
340
|
interface SyncRecord {
|
|
302
341
|
id: number;
|
|
303
342
|
time: Timestamp;
|
|
@@ -704,6 +743,12 @@ interface UninstallResult {
|
|
|
704
743
|
mode: "commit" | "pullRequest";
|
|
705
744
|
revision?: string;
|
|
706
745
|
pullRequestUrl?: string;
|
|
746
|
+
/**
|
|
747
|
+
* What the change could not keep up to date, e.g. the custom portal's route types
|
|
748
|
+
* (`portal/src/cicord-routes.d.ts`) when `cicord portal typegen` failed: fix and commit it,
|
|
749
|
+
* or the portal's CI check fails.
|
|
750
|
+
*/
|
|
751
|
+
warnings?: string[];
|
|
707
752
|
}
|
|
708
753
|
type ConfigScope = "server" | "base";
|
|
709
754
|
interface UpdatePluginConfigRequest {
|
|
@@ -1280,6 +1325,12 @@ interface StoreUpdateResult {
|
|
|
1280
1325
|
message?: string;
|
|
1281
1326
|
/** Health of every instance (commit mode, once the new revision is active). */
|
|
1282
1327
|
instances: UpdatedInstance[];
|
|
1328
|
+
/**
|
|
1329
|
+
* What the change could not keep up to date, e.g. the custom portal's route types
|
|
1330
|
+
* (`portal/src/cicord-routes.d.ts`) when `cicord portal typegen` failed: fix and commit it,
|
|
1331
|
+
* or the portal's CI check fails.
|
|
1332
|
+
*/
|
|
1333
|
+
warnings?: string[];
|
|
1283
1334
|
}
|
|
1284
1335
|
/** Result of a plugin install (setup wizard §10 and Store §11). */
|
|
1285
1336
|
interface InstallResult {
|
|
@@ -1291,6 +1342,12 @@ interface InstallResult {
|
|
|
1291
1342
|
revision?: string;
|
|
1292
1343
|
mode: "commit" | "pullRequest";
|
|
1293
1344
|
pullRequestUrl?: string;
|
|
1345
|
+
/**
|
|
1346
|
+
* What the change could not keep up to date, e.g. the custom portal's route types
|
|
1347
|
+
* (`portal/src/cicord-routes.d.ts`) when `cicord portal typegen` failed: fix and commit it,
|
|
1348
|
+
* or the portal's CI check fails.
|
|
1349
|
+
*/
|
|
1350
|
+
warnings?: string[];
|
|
1294
1351
|
}
|
|
1295
1352
|
/** `POST /registries` request. */
|
|
1296
1353
|
interface AddRegistryRequest {
|
|
@@ -1327,6 +1384,13 @@ type AdminEvent = {
|
|
|
1327
1384
|
} | {
|
|
1328
1385
|
type: "sync" | "plugins" | "analytics";
|
|
1329
1386
|
server?: string;
|
|
1387
|
+
} |
|
|
1388
|
+
/**
|
|
1389
|
+
* What the plugin Store lists changed without a new revision (a registry refresh found
|
|
1390
|
+
* new releases or updates). A new revision is a `sync` event without server.
|
|
1391
|
+
*/
|
|
1392
|
+
{
|
|
1393
|
+
type: "store";
|
|
1330
1394
|
};
|
|
1331
1395
|
/** Periods of `GET /portal/{server}/analytics`. */
|
|
1332
1396
|
type PortalAnalyticsPeriod = "7d" | "30d" | "90d";
|
|
@@ -1755,8 +1819,24 @@ export declare class CicordClient {
|
|
|
1755
1819
|
resources: (server: string, options?: CallOptions) => Promise<ServerResources>;
|
|
1756
1820
|
/** `GET /servers/{server}/plan` (admin). */
|
|
1757
1821
|
plan: (server: string, options?: CallOptions) => Promise<Plan>;
|
|
1758
|
-
/**
|
|
1759
|
-
|
|
1822
|
+
/**
|
|
1823
|
+
* `POST /servers/{server}/sync` (admin) — reconcile now. Rejects with `paused` (409)
|
|
1824
|
+
* while enforcement is paused, unless `resume` is set (resumes, then syncs).
|
|
1825
|
+
*/
|
|
1826
|
+
sync: (server: string, options?: CallOptions & {
|
|
1827
|
+
resume?: boolean;
|
|
1828
|
+
}) => Promise<SyncResult>;
|
|
1829
|
+
/** `GET /servers/{server}/pause` (moderator) — the pause and the pending plan. */
|
|
1830
|
+
pauseState: (server: string, options?: CallOptions) => Promise<PauseState>;
|
|
1831
|
+
/**
|
|
1832
|
+
* `POST /servers/{server}/pause` (moderator) — pauses enforcement: nothing is applied to
|
|
1833
|
+
* the server until it is resumed.
|
|
1834
|
+
*/
|
|
1835
|
+
pause: (server: string, body?: {
|
|
1836
|
+
reason?: string;
|
|
1837
|
+
}, options?: CallOptions) => Promise<PauseResult>;
|
|
1838
|
+
/** `POST /servers/{server}/resume` (moderator) — the next revision or sync applies again. */
|
|
1839
|
+
resume: (server: string, options?: CallOptions) => Promise<ResumeResult>;
|
|
1760
1840
|
/** `GET /servers/{server}/audit?before=&limit=` (moderator), newest first. */
|
|
1761
1841
|
audit: (server: string, query?: AuditQuery, options?: CallOptions) => Promise<AuditEntry[]>;
|
|
1762
1842
|
/** `GET /servers/{server}/plugins` (moderator): every instance. */
|
|
@@ -1960,5 +2040,5 @@ export declare class CicordApiError extends Error {
|
|
|
1960
2040
|
static fromResponse(status: number, statusText: string, body: Json | string | undefined): CicordApiError;
|
|
1961
2041
|
}
|
|
1962
2042
|
export declare function isCicordApiError(error: unknown, code?: ApiErrorCode): error is CicordApiError;
|
|
1963
|
-
export type { AccessRole, AddRegistryRequest, AdminEvent, AnalyticsCatalog, AnalyticsCatalogEntry, AnalyticsKind, AnalyticsKpi, AnalyticsLabel, AnalyticsLabelKind, AnalyticsMetric, AnalyticsMissing, AnalyticsPeriod, AnalyticsPoint, AnalyticsRange, AnalyticsRanked, AnalyticsSerie, AnalyticsSeries, AnalyticsSeriesParams, AnalyticsStatus, AnalyticsStep, AnalyticsSummary, AnalyticsSummaryQuery, AnalyticsUnit, ApiErrorBody, ApiErrorCode, AuditEntry, AuditQuery, AuthMode, BotStatus, ButtonStyle, CallOptions, CicordClientOptions, ConfigScope, Diagnostic, Drift, EventStream, EventStreamOptions, ExchangeLinkTokenOptions, FetchLike, HealthState, HistoryLike, HistoryQuery, HumanError, HumanErrorCode, InstallResult, InstalledPluginVersion, InteractionResult, InteractionStatus, Items, Json, Leaderboard, LeaderboardEntry, LevelsStanding, ListDiff, LocationLike, Me, MeServer, Message, MessageButton, MessageEmbed, MessageRow, MessageSelect, MessageSelectOption, OfficialPluginRoutes, OnboardingAnswers, OnboardingApi, OnboardingCompleteRequest, OnboardingCompleteResponse, OnboardingOption, OnboardingRole, OnboardingStep, OnboardingSteps, OptionalArg, Page, PageParams, PermissionDiff, Plan, PlanAction, PlanBlocked, PlanChange, PlanFieldChange, PlanKind, PlanNote, PluginCommandSummary, PluginInstance, PluginInstanceStatus, PluginListParams, PluginManifestSummary, PluginRouteRegistry, PluginRoutes, PluginSortKey, PluginTrust, PluginUpdate, PluginUpdateFiles, PluginUpdateInstance, PluginUpdateKind, PluginUpdateLevel, PollResults, PortalAnalytics, PortalAnalyticsPeriod, PortalLink, PortalLinkIcon, PortalLocale, PortalMe, PortalMember, PortalPages, PortalPlugin, PortalRole, PortalServer, PortalTheme, Query, RemotePlanResult, RequestOptions, ResourceCategory, ResourceChannel, ResourceRole, Revision, RouteAccess, RouteCallOptions, RouteEntry, RouteInput, RouteKey, RouteKeyOf, RouteMethod, RouteParams, RouteResponseOf, RoutesOf, RuntimeMode, RuntimeStatus, ServerAssetKind, ServerAssetResult, ServerDetail, ServerResources, ServerSentEvent, ServerStatus, SimChannel, SimCommand, SimCommandOption, SimCommandOptionType, SimCommandRequest, SimComponentRequest, SimMember, SimModal, SimModalRequest, SimModalRow, SimRole, SimSendMessageRequest, SimServer, SimState, SimTextInput, SortOrder, StoreDetail, StoreInstallRequest, StoreInstallation, StorePlugin, StorePluginParams, StorePluginSortKey, StoreSignature, StoreSource, StoreSourceKind, StoreSourceSummary, StoreTrust, StoreUpdateRequest, StoreUpdateResult, StoreUpdateReview, StoredSession, StreamFetch, SyncRecord, SyncRecordStatus, SyncResult, SyncState, Ticket, TicketList, TicketStatus, Timestamp, TokenSession, TokenStore, TypedPluginRoutes, UninstallResult, UntypedRoute, UpdatePluginConfigRequest, UpdatedInstance, User, WriteBackResult, WriteResult };
|
|
2043
|
+
export type { AccessRole, AddRegistryRequest, AdminEvent, AnalyticsCatalog, AnalyticsCatalogEntry, AnalyticsKind, AnalyticsKpi, AnalyticsLabel, AnalyticsLabelKind, AnalyticsMetric, AnalyticsMissing, AnalyticsPeriod, AnalyticsPoint, AnalyticsRange, AnalyticsRanked, AnalyticsSerie, AnalyticsSeries, AnalyticsSeriesParams, AnalyticsStatus, AnalyticsStep, AnalyticsSummary, AnalyticsSummaryQuery, AnalyticsUnit, ApiErrorBody, ApiErrorCode, AuditEntry, AuditQuery, AuthMode, BotStatus, ButtonStyle, CallOptions, CicordClientOptions, ConfigScope, Diagnostic, Drift, EventStream, EventStreamOptions, ExchangeLinkTokenOptions, FetchLike, HealthState, HistoryLike, HistoryQuery, HumanError, HumanErrorCode, InstallResult, InstalledPluginVersion, InteractionResult, InteractionStatus, Items, Json, Leaderboard, LeaderboardEntry, LevelsStanding, ListDiff, LocationLike, Me, MeServer, Message, MessageButton, MessageEmbed, MessageRow, MessageSelect, MessageSelectOption, OfficialPluginRoutes, OnboardingAnswers, OnboardingApi, OnboardingCompleteRequest, OnboardingCompleteResponse, OnboardingOption, OnboardingRole, OnboardingStep, OnboardingSteps, OptionalArg, Page, PageParams, PauseInfo, PauseResult, PauseState, PermissionDiff, Plan, PlanAction, PlanBlocked, PlanChange, PlanFieldChange, PlanKind, PlanNote, PluginCommandSummary, PluginInstance, PluginInstanceStatus, PluginListParams, PluginManifestSummary, PluginRouteRegistry, PluginRoutes, PluginSortKey, PluginTrust, PluginUpdate, PluginUpdateFiles, PluginUpdateInstance, PluginUpdateKind, PluginUpdateLevel, PollResults, PortalAnalytics, PortalAnalyticsPeriod, PortalLink, PortalLinkIcon, PortalLocale, PortalMe, PortalMember, PortalPages, PortalPlugin, PortalRole, PortalServer, PortalTheme, Query, RemotePlanResult, RequestOptions, ResourceCategory, ResourceChannel, ResourceRole, ResumeResult, Revision, RouteAccess, RouteCallOptions, RouteEntry, RouteInput, RouteKey, RouteKeyOf, RouteMethod, RouteParams, RouteResponseOf, RoutesOf, RuntimeMode, RuntimeStatus, ServerAssetKind, ServerAssetResult, ServerDetail, ServerResources, ServerSentEvent, ServerStatus, SimChannel, SimCommand, SimCommandOption, SimCommandOptionType, SimCommandRequest, SimComponentRequest, SimMember, SimModal, SimModalRequest, SimModalRow, SimRole, SimSendMessageRequest, SimServer, SimState, SimTextInput, SortOrder, StoreDetail, StoreInstallRequest, StoreInstallation, StorePlugin, StorePluginParams, StorePluginSortKey, StoreSignature, StoreSource, StoreSourceKind, StoreSourceSummary, StoreTrust, StoreUpdateRequest, StoreUpdateResult, StoreUpdateReview, StoredSession, StreamFetch, SyncRecord, SyncRecordStatus, SyncResult, SyncState, Ticket, TicketList, TicketStatus, Timestamp, TokenSession, TokenStore, TypedPluginRoutes, UninstallResult, UntypedRoute, UpdatePluginConfigRequest, UpdatedInstance, User, WriteBackResult, WriteResult };
|
|
1964
2044
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -631,6 +631,7 @@ var CicordClient = class {
|
|
|
631
631
|
break;
|
|
632
632
|
case "status":
|
|
633
633
|
case "stopping":
|
|
634
|
+
case "store":
|
|
634
635
|
onEvent({ type: e.event });
|
|
635
636
|
break;
|
|
636
637
|
case "sync":
|
|
@@ -658,8 +659,29 @@ var CicordClient = class {
|
|
|
658
659
|
resources: (server, options) => this.#api("GET", `/servers/${seg(server)}/resources`, options),
|
|
659
660
|
/** `GET /servers/{server}/plan` (admin). */
|
|
660
661
|
plan: (server, options) => this.#api("GET", `/servers/${seg(server)}/plan`, options),
|
|
661
|
-
/**
|
|
662
|
-
|
|
662
|
+
/**
|
|
663
|
+
* `POST /servers/{server}/sync` (admin) — reconcile now. Rejects with `paused` (409)
|
|
664
|
+
* while enforcement is paused, unless `resume` is set (resumes, then syncs).
|
|
665
|
+
*/
|
|
666
|
+
sync: (server, options = {}) => {
|
|
667
|
+
const { resume, ...rest } = options;
|
|
668
|
+
return this.#api("POST", `/servers/${seg(server)}/sync`, {
|
|
669
|
+
...rest,
|
|
670
|
+
...resume ? { body: { resume: true } } : {}
|
|
671
|
+
});
|
|
672
|
+
},
|
|
673
|
+
/** `GET /servers/{server}/pause` (moderator) — the pause and the pending plan. */
|
|
674
|
+
pauseState: (server, options) => this.#api("GET", `/servers/${seg(server)}/pause`, options),
|
|
675
|
+
/**
|
|
676
|
+
* `POST /servers/{server}/pause` (moderator) — pauses enforcement: nothing is applied to
|
|
677
|
+
* the server until it is resumed.
|
|
678
|
+
*/
|
|
679
|
+
pause: (server, body = {}, options) => this.#api("POST", `/servers/${seg(server)}/pause`, {
|
|
680
|
+
...options,
|
|
681
|
+
body
|
|
682
|
+
}),
|
|
683
|
+
/** `POST /servers/{server}/resume` (moderator) — the next revision or sync applies again. */
|
|
684
|
+
resume: (server, options) => this.#api("POST", `/servers/${seg(server)}/resume`, options),
|
|
663
685
|
/** `GET /servers/{server}/audit?before=&limit=` (moderator), newest first. */
|
|
664
686
|
audit: async (server, query = {}, options) => (await this.#api("GET", `/servers/${seg(server)}/audit`, {
|
|
665
687
|
query: {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/routes.ts","../src/sse.ts","../src/client.ts","../src/onboarding.ts","../src/showcase.ts"],"sourcesContent":["import type { ApiErrorCode, Diagnostic, Json } from \"./types.ts\";\n\nconst CODE_BY_STATUS: Record<number, ApiErrorCode> = {\n 400: \"invalid\",\n 401: \"unauthenticated\",\n 403: \"forbidden\",\n 404: \"not_found\",\n 405: \"invalid\",\n 409: \"conflict\",\n 413: \"invalid\",\n 415: \"invalid\",\n 421: \"forbidden\",\n 422: \"invalid\",\n 500: \"internal\",\n 503: \"unavailable\",\n};\n\n/** Error code for a status when the body carries none (plain-text 404s, proxies…). */\nexport function codeForStatus(status: number): ApiErrorCode {\n return CODE_BY_STATUS[status] ?? (status >= 500 ? \"internal\" : `http_${status}`);\n}\n\n/**\n * Error raised for every non-2xx response of the runtime API (and for network failures,\n * with `status: 0` and code `\"network\"`).\n */\nexport class CicordApiError extends Error {\n /** `snake_case` error code from the body (`{\"error\": {\"code\"}}`), or derived from the status. */\n readonly code: ApiErrorCode;\n /** HTTP status, 0 for network errors. */\n readonly status: number;\n /** Validation diagnostics (422 on config updates, `POST /plan`). */\n readonly diagnostics: Diagnostic[];\n /** Parsed response body (JSON or text), when any. */\n readonly body: Json | string | undefined;\n /** How to fix it, when the runtime explains the error (plan / sync failures). */\n readonly hint: string | undefined;\n /** Raw technical text behind `message`, when the runtime explains the error. */\n readonly details: string | undefined;\n /** Humanized error code (`HumanErrorCode`), when the runtime explains the error. */\n readonly reason: string | undefined;\n\n constructor(init: {\n code: ApiErrorCode;\n status: number;\n message: string;\n diagnostics?: Diagnostic[];\n body?: Json | string;\n cause?: unknown;\n hint?: string | undefined;\n details?: string | undefined;\n reason?: string | undefined;\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = \"CicordApiError\";\n this.code = init.code;\n this.status = init.status;\n this.diagnostics = init.diagnostics ?? [];\n this.body = init.body;\n this.hint = init.hint;\n this.details = init.details;\n this.reason = init.reason;\n }\n\n /** Builds the error from a response status and its (already parsed) body. */\n static fromResponse(\n status: number,\n statusText: string,\n body: Json | string | undefined,\n ): CicordApiError {\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n const error = (body as { error?: unknown }).error;\n if (error && typeof error === \"object\" && !Array.isArray(error)) {\n const e = error as {\n code?: unknown;\n message?: unknown;\n diagnostics?: unknown;\n hint?: unknown;\n details?: unknown;\n reason?: unknown;\n };\n const str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n return new CicordApiError({\n code: typeof e.code === \"string\" && e.code ? e.code : codeForStatus(status),\n status,\n message:\n typeof e.message === \"string\" && e.message ? e.message : statusText || `HTTP ${status}`,\n diagnostics: Array.isArray(e.diagnostics) ? e.diagnostics : [],\n body,\n hint: str(e.hint),\n details: str(e.details),\n reason: str(e.reason),\n });\n }\n }\n const text = typeof body === \"string\" ? body.trim() : \"\";\n return new CicordApiError({\n code: codeForStatus(status),\n status,\n message: text && text.length <= 200 ? text : statusText || `HTTP ${status}`,\n ...(body === undefined ? {} : { body }),\n });\n }\n}\n\nexport function isCicordApiError(error: unknown, code?: ApiErrorCode): error is CicordApiError {\n return error instanceof CicordApiError && (code === undefined || error.code === code);\n}\n","/**\n * Typed plugin routes. A portal learns the routes of the plugins of its repository from\n * `src/cicord-routes.d.ts`, generated by `cicord portal typegen` (and `cicord portal build`): a\n * module augmentation of `PluginRouteRegistry`, keyed by plugin name then route key, with\n * the access level and the query, body and response types declared by the plugin's route\n * contract (plugin.yaml `spec.routes.types`).\n *\n * ```ts\n * const levels = client.routes(\"levels\", server.key, instance); // instance: { bot, instance }\n * const board = await levels.call(\"GET /leaderboard\", { query: { limit: 10 } }); // board.items…\n * const poll = await client.routes(\"polls\", server.key, p).call(\"GET /polls/:id\", { params: { id } });\n * ```\n */\nimport type { CallOptions, Query } from \"./client.ts\";\nimport type {\n OnboardingAnswers,\n OnboardingCompleteResponse,\n OnboardingSteps,\n} from \"./onboarding.ts\";\nimport type { Leaderboard, TicketList, TicketStatus } from \"./showcase.ts\";\nimport type { Json } from \"./types.ts\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n/** \"<METHOD> /path\", `:name` segments being parameters: \"GET /polls/:id\". */\nexport type RouteKey = `${RouteMethod} /${string}`;\n/** Access level of a route (`definePlugin({ routes })`). */\nexport type RouteAccess = \"public\" | \"member\" | \"moderator\" | \"admin\";\n\n/** `{ id: string }` for \"GET /polls/:id\". */\nexport type RouteParams<K extends string> = K extends `${string}/:${infer Rest}`\n ? Rest extends `${infer Name}/${infer Tail}`\n ? { [P in Name]: string } & RouteParams<`/${Tail}`>\n : { [P in Rest]: string }\n : {};\n\n/** A route whose plugin declares no types: any query and body, a JSON response. */\nexport interface UntypedRoute {\n query?: Query;\n body?: unknown;\n response: Json;\n}\n\n/**\n * One route of `PluginRouteRegistry`: its access level and, when the plugin's contract\n * `Contract` declares route `K`, its `query`, `body` and `response` (absent: `204`).\n */\nexport type RouteEntry<\n A extends RouteAccess = RouteAccess,\n Contract = {},\n K extends string = never,\n> = { readonly access: A } & ([K] extends [never]\n ? UntypedRoute\n : K extends keyof Contract\n ? Contract[K]\n : UntypedRoute);\n\n/**\n * Routes of the plugins of the repository, by plugin name then route key. Empty here:\n * `src/cicord-routes.d.ts` (generated by `cicord portal typegen`) fills it.\n */\nexport interface PluginRouteRegistry {}\n\n/** levels `GET /me`: the viewer's own standing. */\nexport interface LevelsStanding {\n userId: string;\n /** From 1, null when the viewer has no XP yet. */\n rank: number | null;\n xp: number;\n level: number;\n /** XP earned inside the current level. */\n current: number;\n /** XP needed for the next level. */\n needed: number;\n}\n\n/** polls `GET /polls/:id`. */\nexport interface PollResults {\n id: string;\n question: string;\n status: \"open\" | \"closed\";\n multiple: boolean;\n createdAt: string;\n closesAt: string;\n closedAt: string | null;\n choices: { label: string; votes: number }[];\n voters: number;\n}\n\n/**\n * Routes of the official plugins (the `cicord` source), used for a plugin that the generated\n * registry does not list: the reference portal type-checks in a repository without them.\n */\nexport interface OfficialPluginRoutes {\n levels: {\n \"GET /leaderboard\": {\n readonly access: \"public\";\n query: { limit?: number };\n response: Leaderboard;\n };\n \"GET /me\": { readonly access: \"member\"; response: LevelsStanding };\n };\n polls: { \"GET /polls/:id\": { readonly access: \"public\"; response: PollResults } };\n tickets: {\n \"GET /tickets\": {\n readonly access: \"moderator\";\n query: { status?: TicketStatus };\n response: TicketList;\n };\n \"GET /tickets/:id\": RouteEntry<\"moderator\">;\n };\n onboarding: {\n \"GET /steps\": { readonly access: \"member\"; response: OnboardingSteps };\n \"POST /complete\": {\n readonly access: \"member\";\n body: { answers: OnboardingAnswers };\n response: OnboardingCompleteResponse;\n };\n };\n}\n\n/** The routes of plugin `N`: generated registry, else official plugin, else untyped. */\nexport type RoutesOf<N extends string> = N extends keyof PluginRouteRegistry\n ? PluginRouteRegistry[N]\n : N extends keyof OfficialPluginRoutes\n ? OfficialPluginRoutes[N]\n : { [K in RouteKey]: RouteEntry };\n\n/** Route keys of plugin `N` (optionally only those of `M` methods). */\nexport type RouteKeyOf<N extends string, M extends RouteMethod = RouteMethod> = Extract<\n keyof RoutesOf<N>,\n `${M} /${string}`\n>;\n\n/** The JSON a route answers with (`undefined` for routes declaring no response: 204). */\nexport type RouteResponseOf<E> = E extends { response: infer R } ? R : undefined;\n\ntype ParamsArg<K extends string> = keyof RouteParams<K> extends never\n ? { params?: Record<string, never> }\n : { params: RouteParams<K> };\ntype QueryArg<E> = E extends { query: infer Q }\n ? {} extends Q\n ? { query?: Q }\n : { query: Q }\n : E extends { query?: infer Q }\n ? { query?: Q }\n : { query?: undefined };\ntype BodyArg<E> = E extends { body: infer B }\n ? { body: B }\n : E extends { body?: infer B }\n ? { body?: B }\n : { body?: undefined };\n\n/** What a call needs: `params` (from the key), `query` and `body` (as declared). */\nexport type RouteInput<K extends string, E> = ParamsArg<K> & QueryArg<E> & BodyArg<E>;\nexport type RouteCallOptions<K extends string, E> = RouteInput<K, E> &\n CallOptions & { headers?: Record<string, string> };\n\n/** Makes the options argument optional when nothing in it is required. */\nexport type OptionalArg<T> = {} extends T ? [options?: T] : [options: T];\n\n/** Typed calls to the routes of one instance of plugin `N`. */\nexport interface TypedPluginRoutes<N extends string> {\n readonly plugin: N;\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Calls a route: `call(\"GET /polls/:id\", { params: { id } })`. */\n call<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteCallOptions<K, RoutesOf<N>[K]>>\n ): Promise<RouteResponseOf<RoutesOf<N>[K]>>;\n /** Absolute URL of a route (`GET` routes: links, `<img src>`, EventSource…). */\n url<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteInput<K, RoutesOf<N>[K]>>\n ): string;\n}\n\n/** Splits \"GET /polls/:id\" with `{ id: \"4\" }` into `[\"GET\", \"/polls/4\"]`. */\nexport function resolveRoute(\n route: string,\n params: Record<string, string | number> | undefined = {},\n): [method: RouteMethod, path: string] {\n const space = route.indexOf(\" \");\n const method = route.slice(0, space) as RouteMethod;\n if (space < 0 || ![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method))\n throw new Error(`@cicord/client: invalid route key ${JSON.stringify(route)}`);\n const path = route\n .slice(space + 1)\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n const value = params[segment.slice(1)];\n if (value === undefined || value === \"\")\n throw new Error(`@cicord/client: missing parameter ${segment.slice(1)} of ${route}`);\n // A value taken from the page URL must never climb out of the route (\"..\": another\n // route of the instance, another plugin, another API endpoint with the viewer's\n // cookies). Dots are encoded too, so no segment can be a dot-segment; the runtime\n // reads %2E as a literal dot.\n if (value === \".\" || value === \"..\")\n throw new Error(\n `@cicord/client: invalid parameter ${segment.slice(1)} of ${route}: ${value}`,\n );\n return encodeURIComponent(String(value)).replace(/\\./g, \"%2E\");\n })\n .join(\"/\");\n return [method, path];\n}\n","/**\n * Minimal Server-Sent Events client built on fetch (not EventSource), so it can send an\n * `Authorization` header, works in Node 24 and is easy to test with a mocked fetch.\n */\n\nexport interface ServerSentEvent {\n /** Event type (`event:` field), \"message\" by default. */\n event: string;\n data: string;\n id: string;\n}\n\nexport interface EventStreamOptions {\n onEvent: (event: ServerSentEvent) => void;\n /** Called on connection errors; the stream reconnects afterwards unless closed. */\n onError?: (error: unknown) => void;\n /** Called when a connection is (re)established. */\n onOpen?: () => void;\n /** Delay before reconnecting, in ms (updated by the server's `retry:` field). Default 2000. */\n retryMs?: number;\n /** Stop after the first disconnection instead of reconnecting. */\n once?: boolean;\n /**\n * Reconnect when nothing (event or comment) arrives for this long, in ms: a proxy can\n * keep the connection open after the server went away. Use it with a server that sends\n * keep-alive comments more often (Cicord's streams: every 25 s). Default: no limit.\n */\n idleTimeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface EventStream {\n close: () => void;\n /** Resolves when the stream is closed for good. */\n readonly closed: Promise<void>;\n}\n\nexport type StreamFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/** Incremental SSE parser (https://html.spec.whatwg.org/multipage/server-sent-events.html). */\nexport class SseParser {\n #buffer = \"\";\n #data: string[] = [];\n #event = \"\";\n #lastId = \"\";\n retry: number | undefined;\n readonly #emit: (event: ServerSentEvent) => void;\n\n constructor(emit: (event: ServerSentEvent) => void) {\n this.#emit = emit;\n }\n\n push(chunk: string): void {\n this.#buffer += chunk;\n let index: number;\n while ((index = this.#buffer.search(/\\r\\n|\\r|\\n/)) >= 0) {\n const line = this.#buffer.slice(0, index);\n const sep = this.#buffer.startsWith(\"\\r\\n\", index) ? 2 : 1;\n // A lone trailing \"\\r\" might be the first half of \"\\r\\n\": wait for more input.\n if (sep === 1 && this.#buffer[index] === \"\\r\" && index === this.#buffer.length - 1) break;\n this.#buffer = this.#buffer.slice(index + sep);\n this.#line(line);\n }\n }\n\n #line(line: string): void {\n if (line === \"\") {\n if (this.#data.length > 0) {\n this.#emit({\n event: this.#event || \"message\",\n data: this.#data.join(\"\\n\"),\n id: this.#lastId,\n });\n }\n this.#data = [];\n this.#event = \"\";\n return;\n }\n if (line.startsWith(\":\")) return;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n let value = colon < 0 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n switch (field) {\n case \"data\":\n this.#data.push(value);\n break;\n case \"event\":\n this.#event = value;\n break;\n case \"id\":\n if (!value.includes(\"\\0\")) this.#lastId = value;\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) this.retry = Number(value);\n break;\n }\n }\n\n get lastEventId(): string {\n return this.#lastId;\n }\n}\n\nexport function openEventStream(\n fetcher: StreamFetch,\n url: string,\n init: RequestInit,\n options: EventStreamOptions,\n): EventStream {\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n if (options.signal?.aborted) controller.abort();\n let retryMs = options.retryMs ?? 2000;\n let lastEventId = \"\";\n\n const run = async (): Promise<void> => {\n while (!controller.signal.aborted) {\n const parser = new SseParser(options.onEvent);\n // One controller per connection: the idle watchdog ends it without closing the stream.\n const attempt = new AbortController();\n const endAttempt = (): void => attempt.abort();\n controller.signal.addEventListener(\"abort\", endAttempt, { once: true });\n let idle: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const arm = (): void => {\n if (options.idleTimeoutMs === undefined) return;\n clearTimeout(idle);\n idle = setTimeout(() => {\n timedOut = true;\n attempt.abort();\n }, options.idleTimeoutMs);\n };\n try {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n if (lastEventId) headers.set(\"Last-Event-ID\", lastEventId);\n arm();\n const response = await fetcher(url, { ...init, headers, signal: attempt.signal });\n if (!response.ok || !response.body) {\n throw new Error(`event stream ${url}: HTTP ${response.status}`);\n }\n options.onOpen?.();\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n for (;;) {\n arm();\n const { value, done } = await reader.read();\n if (done) break;\n parser.push(value);\n lastEventId = parser.lastEventId;\n if (parser.retry !== undefined) retryMs = parser.retry;\n }\n if (!controller.signal.aborted)\n options.onError?.(new Error(`event stream ${url}: disconnected`));\n } catch (error) {\n if (controller.signal.aborted) break;\n options.onError?.(\n timedOut\n ? new Error(`event stream ${url}: nothing received for ${options.idleTimeoutMs} ms`)\n : error,\n );\n } finally {\n clearTimeout(idle);\n controller.signal.removeEventListener(\"abort\", endAttempt);\n }\n if (options.once) break;\n await sleep(retryMs, controller.signal);\n }\n options.signal?.removeEventListener(\"abort\", abort);\n };\n\n const closed = run();\n return {\n close: abort,\n closed,\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n }\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n","import { CicordApiError } from \"./errors.ts\";\nimport { resolveRoute, type TypedPluginRoutes } from \"./routes.ts\";\nimport {\n openEventStream,\n type EventStream,\n type EventStreamOptions,\n type ServerSentEvent,\n} from \"./sse.ts\";\nimport type {\n AdminEvent,\n PortalAnalytics,\n PortalAnalyticsPeriod,\n AddRegistryRequest,\n AnalyticsCatalog,\n AnalyticsSeries,\n AnalyticsSeriesParams,\n AnalyticsSummary,\n AnalyticsSummaryQuery,\n AuditEntry,\n AuditQuery,\n InstallResult,\n InteractionResult,\n Items,\n Json,\n HistoryQuery,\n Me,\n Message,\n Page,\n PageParams,\n Plan,\n PluginInstance,\n PluginListParams,\n PortalMe,\n PortalServer,\n RemotePlanResult,\n RuntimeStatus,\n ServerAssetKind,\n ServerAssetResult,\n ServerDetail,\n ServerResources,\n SimCommand,\n SimCommandRequest,\n SimComponentRequest,\n SimModalRequest,\n SimSendMessageRequest,\n SimState,\n StoreDetail,\n StoreInstallRequest,\n StorePlugin,\n StorePluginParams,\n StoreSource,\n StoreSourceSummary,\n StoreUpdateRequest,\n StoreUpdateResult,\n StoreUpdateReview,\n SyncRecord,\n SyncResult,\n TokenSession,\n UninstallResult,\n UpdatePluginConfigRequest,\n User,\n WriteBackResult,\n WriteResult,\n} from \"./types.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/**\n * How browser clients authenticate (https://cicord.dev/docs/reference/http-api/authentication/):\n * - `\"cookie\"` (default): the `cicord_session` cookie, for a portal served by the runtime or\n * on a same-site origin listed in `--cors-origin`;\n * - `\"token\"`: a bearer session token kept in a `TokenStore` and sent as `Authorization`,\n * for sites embedding the SDK on another origin (cicord.yaml `spec.portal.allowedOrigins`).\n */\nexport type AuthMode = \"cookie\" | \"token\";\n\n/** A token-mode session as stored by the client. */\nexport interface StoredSession {\n token: string;\n expiresAt: string;\n}\n\n/** Where token mode keeps the session token. */\nexport interface TokenStore {\n get(): StoredSession | null;\n set(session: StoredSession | null): void;\n}\n\n/** Keeps the token in memory (lost on reload; safest against XSS persistence). */\nexport function memoryTokenStore(): TokenStore {\n let value: StoredSession | null = null;\n return { get: () => value, set: (session) => void (value = session) };\n}\n\n/** Keeps the token in `localStorage` / `sessionStorage` (falls back to memory when unavailable). */\nexport function webStorageTokenStore(\n storage: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | undefined,\n key = \"cicord:session\",\n): TokenStore {\n const memory = memoryTokenStore();\n if (!storage) return memory;\n return {\n get: () => {\n try {\n const raw = storage.getItem(key);\n const parsed = raw ? (JSON.parse(raw) as Partial<StoredSession>) : null;\n return parsed && typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"string\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : null;\n } catch {\n return memory.get();\n }\n },\n set: (session) => {\n try {\n if (session) storage.setItem(key, JSON.stringify(session));\n else storage.removeItem(key);\n } catch {\n memory.set(session);\n }\n },\n };\n}\n\n/** True for absolute http(s) URLs (links from the server config, plugin data…). */\nexport function isSafeUrl(url: string): boolean {\n try {\n const u = new URL(url);\n return u.protocol === \"https:\" || u.protocol === \"http:\";\n } catch {\n return false;\n }\n}\n\nexport interface CicordClientOptions {\n /**\n * Origin (or origin + prefix) of the Cicord runtime, e.g. \"https://cicord.example.org\".\n * Default \"\": same origin as the page.\n */\n baseUrl?: string;\n /** API prefix. Default \"/api/v1\". */\n apiPath?: string;\n /** Auth prefix (https://cicord.dev/docs/reference/http-api/authentication/). Default \"/auth\". */\n authPath?: string;\n /** fetch implementation. Default: the global `fetch`, looked up at call time. */\n fetch?: FetchLike;\n /** Bearer token (runtime token) for machine clients; a function is called per request. */\n token?: string | (() => string | undefined | null);\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /**\n * Fetch credentials mode. Default \"include\" in cookie mode (session cookie, also\n * cross-origin with CORS), \"omit\" in token mode.\n */\n credentials?: RequestCredentials;\n /** Browser auth mode. Default \"cookie\". See `AuthMode`. */\n auth?: AuthMode;\n /**\n * Token mode: where the session token lives. \"local\" (default in browsers) and\n * \"session\" use Web Storage under `storageKey`; \"memory\" forgets it on reload.\n */\n tokenStore?: TokenStore | \"local\" | \"session\" | \"memory\";\n /** Web Storage key of token mode. Default \"cicord:session:<baseUrl>\". */\n storageKey?: string;\n}\n\nexport type Query = Record<string, string | number | boolean | undefined | null>;\n\nexport interface RequestOptions {\n query?: Query;\n /** JSON-serialisable body, or a raw body (Blob, ArrayBuffer, Uint8Array, string, FormData…). */\n body?: unknown;\n /** Content type for raw bodies. */\n contentType?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface CallOptions {\n signal?: AbortSignal;\n}\n\n/** Calls to the routes of one plugin instance (https://cicord.dev/docs/reference/http-api/portal/). */\nexport interface PluginRoutes {\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Absolute URL of a route path. */\n url: (path: string, query?: Query) => string;\n request<T = Json>(method: string, path: string, options?: RequestOptions): Promise<T>;\n get<T = Json>(path: string, query?: Query, options?: CallOptions): Promise<T>;\n post<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n put<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n patch<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n delete<T = Json>(path: string, options?: CallOptions): Promise<T>;\n}\n\n/** Minimal Location / History used by the auth helpers (injectable for tests and SSR). */\nexport interface LocationLike {\n href: string;\n assign?: (url: string) => void;\n}\nexport interface HistoryLike {\n replaceState: (data: unknown, unused: string, url?: string | URL | null) => void;\n readonly state?: unknown;\n}\n\nexport interface ExchangeLinkTokenOptions {\n location?: LocationLike;\n history?: HistoryLike;\n /** Query parameter carrying the token. Default \"cicord_token\". */\n param?: string;\n /** Query parameter carrying the one-time code of a token-mode login. Default \"cicord_code\". */\n codeParam?: string;\n}\n\n/** Query parameters a login may leave in the URL (removed by `exchangeLinkToken`). */\nexport const LOGIN_PARAMS = [\"cicord_token\", \"cicord_code\"] as const;\n\nconst isRawBody = (body: unknown): boolean =>\n typeof body === \"string\" ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n (typeof Blob !== \"undefined\" && body instanceof Blob) ||\n (typeof FormData !== \"undefined\" && body instanceof FormData) ||\n (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream);\n\nconst seg = (value: string): string => encodeURIComponent(value);\n\nfunction trimSlash(value: string): string {\n // A loop, not /\\/+$/: that regex backtracks quadratically on many slashes not at the end.\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\n/** Query string of a paged list (https://cicord.dev/docs/reference/http-api/ \"Data tables\"); empty values are left out. */\nfunction pageQuery(params: PageParams = {}): Query {\n return {\n q: params.q?.trim() || undefined,\n sort: params.sort || undefined,\n order: params.order,\n offset: params.offset,\n limit: params.limit,\n };\n}\n\n/** A Date as RFC 3339 UTC without milliseconds (strings pass through). */\nfunction rfc3339(value: Date | string | undefined): string | undefined {\n if (value === undefined || typeof value === \"string\") return value;\n return value.toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\nfunction withQuery(url: string, query?: Query): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${qs}` : url;\n}\n\n/**\n * Typed client for the Cicord runtime HTTP API v1 (https://cicord.dev/docs/reference/http-api/). Framework-agnostic: works in\n * browsers, Node 24, workers. Every non-2xx response rejects with `CicordApiError`.\n */\nexport class CicordClient {\n readonly baseUrl: string;\n readonly apiPath: string;\n readonly authPath: string;\n readonly authMode: AuthMode;\n readonly #options: CicordClientOptions;\n readonly #store: TokenStore;\n readonly #listeners = new Set<() => void>();\n #pendingLink: Promise<Me> | undefined;\n\n constructor(options: CicordClientOptions = {}) {\n this.#options = options;\n this.baseUrl = trimSlash(options.baseUrl ?? \"\");\n this.apiPath = trimSlash(options.apiPath ?? \"/api/v1\");\n this.authPath = trimSlash(options.authPath ?? \"/auth\");\n this.authMode = options.auth ?? \"cookie\";\n this.#store = resolveStore(\n options.tokenStore,\n options.storageKey ?? `cicord:session:${this.baseUrl}`,\n );\n }\n\n // ─────────────────────────────────────────────────────────── token-mode session\n\n /** The token-mode session, or null (cookie mode, logged out or expired). */\n session(): StoredSession | null {\n if (this.authMode !== \"token\") return null;\n const s = this.#store.get();\n if (s && Date.parse(s.expiresAt) <= Date.now()) {\n this.#setSession(null);\n return null;\n }\n return s;\n }\n\n /** Called when the token-mode session changes (login, logout, expiry, revocation). */\n onSessionChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n #setSession(session: StoredSession | null): void {\n this.#store.set(session);\n for (const listener of this.#listeners) listener();\n }\n\n #adopt(session: TokenSession): Me {\n this.#setSession({ token: session.token, expiresAt: session.expiresAt });\n return session.me;\n }\n\n // ─────────────────────────────────────────────────────────── transport\n\n /** Absolute URL of a path relative to the runtime origin (e.g. \"/api/v1/me\"). */\n url(path: string, query?: Query): string {\n return withQuery(`${this.baseUrl}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n /** URL of an API path (e.g. \"/me\" → \"/api/v1/me\"). */\n apiUrl(path: string, query?: Query): string {\n return this.url(`${this.apiPath}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n #headers(extra?: Record<string, string>): Headers {\n const headers = new Headers(this.#options.headers);\n // CSRF protection (https://cicord.dev/docs/reference/http-api/authentication/): the runtime rejects cookie-authenticated\n // state-changing requests without this header.\n headers.set(\"X-Cicord-Request\", \"1\");\n const token =\n (typeof this.#options.token === \"function\" ? this.#options.token() : this.#options.token) ??\n this.session()?.token;\n if (token) headers.set(\"Authorization\", `Bearer ${token}`);\n for (const [k, v] of Object.entries(extra ?? {})) headers.set(k, v);\n return headers;\n }\n\n #fetch: FetchLike = (input, init) => {\n const impl = this.#options.fetch ?? globalThis.fetch;\n if (!impl) throw new Error(\"@cicord/client: no fetch implementation available\");\n return impl(input, init);\n };\n\n /** Sends a request to an absolute runtime path (no API prefix added). */\n async request<T = Json>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const headers = this.#headers(options.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n if (isRawBody(options.body)) {\n body = options.body as BodyInit;\n if (options.contentType) headers.set(\"Content-Type\", options.contentType);\n } else {\n body = JSON.stringify(options.body);\n headers.set(\"Content-Type\", options.contentType ?? \"application/json\");\n }\n }\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n credentials: this.#credentials(),\n ...(body === undefined ? {} : { body }),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n\n let response: Response;\n try {\n response = await this.#fetch(this.url(path, options.query), init);\n } catch (cause) {\n if (options.signal?.aborted) throw cause;\n throw new CicordApiError({\n code: \"network\",\n status: 0,\n message: cause instanceof Error ? cause.message : \"network error\",\n cause,\n });\n }\n\n const parsed = await readBody(response);\n if (!response.ok) {\n // A revoked or expired token: forget it so the app shows the logged-out state.\n if (response.status === 401 && this.session()?.token && !this.#options.token)\n this.#setSession(null);\n throw CicordApiError.fromResponse(response.status, response.statusText, parsed);\n }\n return parsed as T;\n }\n\n #credentials(): RequestCredentials {\n return this.#options.credentials ?? (this.authMode === \"token\" ? \"omit\" : \"include\");\n }\n\n #api<T>(method: string, path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(method, `${this.apiPath}${path}`, options);\n }\n\n // ─────────────────────────────────────────────────────────── me & auth (§1, §2)\n\n /** `GET /api/v1/me`. Rejects with code `unauthenticated` when there is no session. */\n me(options?: CallOptions): Promise<Me> {\n return this.#api<Me>(\"GET\", \"/me\", options);\n }\n\n /** Like `me()`, but resolves `null` instead of rejecting when not logged in. */\n async meOrNull(options?: CallOptions): Promise<Me | null> {\n try {\n return await this.me(options);\n } catch (error) {\n if (error instanceof CicordApiError && error.code === \"unauthenticated\") return null;\n throw error;\n }\n }\n\n readonly auth = {\n /**\n * URL that starts the Discord OAuth2 login and comes back to `redirect` (a path on the\n * portal; default: the current page).\n */\n loginUrl: (redirect?: string): string => {\n if (this.authMode === \"token\") {\n // The runtime redirects back with ?cicord_code=… to this absolute URL, which must be\n // on an allowed origin (spec.portal.allowedOrigins or --cors-origin).\n const here = globalLocation()?.href;\n const target =\n redirect !== undefined && here ? new URL(redirect, here).toString() : (redirect ?? here);\n return this.url(`${this.authPath}/login`, { mode: \"token\", redirect: target });\n }\n const target = redirect ?? currentPath();\n return this.url(`${this.authPath}/login`, target ? { redirect: target } : undefined);\n },\n\n /** Navigates the browser to the login URL. */\n login: (redirect?: string, location: LocationLike | undefined = globalLocation()): void => {\n const url = this.auth.loginUrl(redirect);\n if (location?.assign) location.assign(url);\n else if (location) location.href = url;\n else throw new Error(\"@cicord/client: auth.login() needs a browser location\");\n },\n\n /** `POST /auth/link` with an explicit token (stores the session token in token mode). */\n link: async (token: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/link`, { body: { token }, ...options });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/link`, {\n body: { token, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** Token mode: `POST /auth/token` — redeems the one-time code of an OAuth login. */\n redeem: async (code: string, options?: CallOptions): Promise<Me> =>\n this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/token`, {\n body: { code },\n ...options,\n }),\n ),\n\n /**\n * Reads `cicord_token` from the current URL (a signed link from `ctx.portal.link()`),\n * removes it from the address bar right away (so it is neither bookmarked nor sent twice),\n * and exchanges it for a session. Resolves `null` when the URL has no token.\n * Calls made while an exchange is in flight share it (safe under React StrictMode).\n */\n exchangeLinkToken: (options: ExchangeLinkTokenOptions = {}): Promise<Me | null> => {\n const location = options.location ?? globalLocation();\n const param = options.param ?? \"cicord_token\";\n const codeParam = options.codeParam ?? \"cicord_code\";\n if (!location) return Promise.resolve(null);\n const url = new URL(location.href);\n const token = url.searchParams.get(param);\n // A token-mode OAuth login comes back with a one-time code.\n const code = this.authMode === \"token\" ? url.searchParams.get(codeParam) : null;\n if (!token && !code) return this.#pendingLink ?? Promise.resolve(null);\n\n url.searchParams.delete(param);\n url.searchParams.delete(codeParam);\n const history = options.history ?? globalHistory();\n const clean = `${url.pathname}${url.search}${url.hash}`;\n if (history) history.replaceState(history.state ?? null, \"\", clean);\n else location.href = url.toString();\n\n const exchange = token ? this.auth.link(token) : this.auth.redeem(code as string);\n const pending = exchange.finally(() => {\n if (this.#pendingLink === pending) this.#pendingLink = undefined;\n });\n this.#pendingLink = pending;\n return pending;\n },\n\n /** `POST /auth/dev-login` — `cicord dev` only (stores the session token in token mode). */\n devLogin: async (userId: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId },\n ...options,\n });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** `POST /auth/logout` (token mode: revokes the token and forgets it). */\n logout: async (options?: CallOptions): Promise<void> => {\n try {\n await this.request<void>(\"POST\", `${this.authPath}/logout`, options);\n } finally {\n if (this.authMode === \"token\") this.#setSession(null);\n }\n },\n };\n\n // ─────────────────────────────────────────────────────────── portal (§6)\n\n readonly portal = {\n /** `GET /portal/servers` — servers with a portal. */\n servers: async (options?: CallOptions): Promise<PortalServer[]> =>\n (await this.#api<Items<PortalServer>>(\"GET\", \"/portal/servers\", options)).items.map((s) =>\n this.#absolutize(s),\n ),\n /** `GET /portal/{server}`. */\n server: async (server: string, options?: CallOptions): Promise<PortalServer> =>\n this.#absolutize(await this.#api<PortalServer>(\"GET\", `/portal/${seg(server)}`, options)),\n /** `GET /portal/{server}/me` — the viewer as a member of the server. */\n me: (server: string, options?: CallOptions): Promise<PortalMe> =>\n this.#api<PortalMe>(\"GET\", `/portal/${seg(server)}/me`, options),\n /**\n * `GET /portal/{server}/analytics?period=` — server-wide activity for the portal, when\n * the server opts in (`spec.analytics.portal`: members or public; 404 otherwise).\n */\n analytics: (\n server: string,\n period: PortalAnalyticsPeriod = \"30d\",\n options?: CallOptions,\n ): Promise<PortalAnalytics> =>\n this.#api<PortalAnalytics>(\"GET\", `/portal/${seg(server)}/analytics`, {\n query: { period },\n ...options,\n }),\n };\n\n /** Runtime-relative image URLs (logo, banner) resolved against `baseUrl` (embedded portals). */\n #absolutize(server: PortalServer): PortalServer {\n if (!this.baseUrl) return server;\n const abs = (u: string | undefined) => (u && u.startsWith(\"/\") ? this.url(u) : u);\n return {\n ...server,\n theme: { ...server.theme, logo: abs(server.theme.logo) ?? \"\" },\n banner: abs(server.banner) ?? \"\",\n };\n }\n\n /** Routes of a plugin instance: `/api/v1/portal/{server}/plugins/{bot}/{instance}/{path}`. */\n plugin(server: string, bot: string, instance: string): PluginRoutes {\n const prefix = `${this.apiPath}/portal/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`;\n const full = (path: string): string => `${prefix}${path.startsWith(\"/\") ? path : `/${path}`}`;\n const request = <T = Json>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T> => this.request<T>(method, full(path), options);\n const withBody =\n (method: string) =>\n <T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T> =>\n request<T>(method, path, { ...options, ...(body === undefined ? {} : { body }) });\n return {\n server,\n bot,\n instance,\n url: (path, query) => this.url(full(path), query),\n request,\n get: <T = Json>(path: string, query?: Query, options?: CallOptions) =>\n request<T>(\"GET\", path, { ...options, ...(query ? { query } : {}) }),\n post: withBody(\"POST\"),\n put: withBody(\"PUT\"),\n patch: withBody(\"PATCH\"),\n delete: <T = Json>(path: string, options?: CallOptions) =>\n request<T>(\"DELETE\", path, options),\n };\n }\n\n /**\n * Typed calls to the routes of an instance of plugin `plugin` (types from the generated\n * `src/cicord-routes.d.ts`, see `PluginRouteRegistry`). `at` is the instance, typically\n * found in `PortalServer.plugins` by plugin name.\n */\n routes<N extends string>(\n plugin: N,\n server: string,\n at: { bot: string; instance: string },\n ): TypedPluginRoutes<N> {\n const routes = this.plugin(server, at.bot, at.instance);\n type Loose = { params?: Record<string, string>; query?: object; body?: unknown };\n return {\n plugin,\n server,\n bot: at.bot,\n instance: at.instance,\n // async: an invalid parameter rejects like any failed call.\n call: (async (route: string, options: Loose & RequestOptions = {}) => {\n const { params, query, body, ...rest } = options;\n const [method, path] = resolveRoute(route, params);\n return routes.request(method, path, {\n ...rest,\n ...(query ? { query } : {}),\n ...(body === undefined ? {} : { body }),\n });\n }) as TypedPluginRoutes<N>[\"call\"],\n url: ((route: string, options: Loose = {}) => {\n const [, path] = resolveRoute(route, options.params);\n return routes.url(path, options.query as Query | undefined);\n }) as TypedPluginRoutes<N>[\"url\"],\n };\n }\n\n // ─────────────────────────────────────────────────────────── admin (§3–§5)\n\n readonly admin = {\n /**\n * Subscribes to `GET /events` (SSE, moderator): `hello` on every (re)connection, then\n * change hints for the runtime (`status`) and the servers you moderate (`sync`,\n * `plugins`, `analytics`). Reconnects automatically; call `close()` to stop.\n */\n subscribe: (\n onEvent: (event: AdminEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/events\", {\n ...options,\n onEvent: (e) => {\n let data: Record<string, unknown> = {};\n try {\n data = JSON.parse(e.data || \"{}\") as Record<string, unknown>;\n } catch {\n return;\n }\n const server = typeof data.server === \"string\" ? data.server : undefined;\n switch (e.event) {\n case \"hello\":\n onEvent({\n type: \"hello\",\n version: typeof data.version === \"string\" ? data.version : \"\",\n revision: typeof data.revision === \"string\" ? data.revision : \"\",\n });\n break;\n case \"status\":\n case \"stopping\":\n onEvent({ type: e.event });\n break;\n case \"sync\":\n case \"plugins\":\n case \"analytics\":\n onEvent(server === undefined ? { type: e.event } : { type: e.event, server });\n break;\n }\n },\n }),\n /** `GET /status` (admin, moderator) — visible servers only. */\n status: (options?: CallOptions): Promise<RuntimeStatus> =>\n this.#api<RuntimeStatus>(\"GET\", \"/status\", options),\n /** `GET /history?limit=&target=` (admin, moderator), newest first. */\n history: async (query: HistoryQuery = {}, options?: CallOptions): Promise<SyncRecord[]> =>\n (\n await this.#api<Items<SyncRecord>>(\"GET\", \"/history\", {\n query: { limit: query.limit, target: query.target },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}` (moderator). */\n server: (server: string, options?: CallOptions): Promise<ServerDetail> =>\n this.#api<ServerDetail>(\"GET\", `/servers/${seg(server)}`, options),\n /** `GET /servers/{server}/resources` (moderator) — roles, categories, channels for pickers. */\n resources: (server: string, options?: CallOptions): Promise<ServerResources> =>\n this.#api<ServerResources>(\"GET\", `/servers/${seg(server)}/resources`, options),\n /** `GET /servers/{server}/plan` (admin). */\n plan: (server: string, options?: CallOptions): Promise<Plan> =>\n this.#api<Plan>(\"GET\", `/servers/${seg(server)}/plan`, options),\n /** `POST /servers/{server}/sync` (admin) — reconcile now. */\n sync: (server: string, options?: CallOptions): Promise<SyncResult> =>\n this.#api<SyncResult>(\"POST\", `/servers/${seg(server)}/sync`, options),\n /** `GET /servers/{server}/audit?before=&limit=` (moderator), newest first. */\n audit: async (\n server: string,\n query: AuditQuery = {},\n options?: CallOptions,\n ): Promise<AuditEntry[]> =>\n (\n await this.#api<Items<AuditEntry>>(\"GET\", `/servers/${seg(server)}/audit`, {\n query: { before: query.before, limit: query.limit },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}/plugins` (moderator): every instance. */\n plugins: async (server: string, options?: CallOptions): Promise<PluginInstance[]> =>\n (await this.#api<Items<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, options))\n .items,\n /**\n * `GET /servers/{server}/plugins?q&sort&order&offset&limit` (moderator): one page of\n * instances. Without `limit` the page holds every instance. Rejects with `invalid` (400)\n * on an unknown sort key.\n */\n pluginsPage: (\n server: string,\n params: PluginListParams = {},\n options?: CallOptions,\n ): Promise<Page<PluginInstance>> =>\n this.#api<Page<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, {\n query: { ...pageQuery(params), updates: params.updates },\n ...options,\n }),\n /** `GET /servers/{server}/plugins/{bot}/{instance}` (moderator). Rejects with `not_found`. */\n plugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<PluginInstance> =>\n this.#api<PluginInstance>(\n \"GET\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `DELETE /servers/{server}/plugins/{bot}/{instance}` (admin): uninstalls the instance from\n * the server (plugin data is kept). Rejects with `invalid` + `diagnostics` (422, something\n * depends on it), `conflict` (409), `forbidden` (403) or `not_found` (404).\n */\n uninstallPlugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<UninstallResult> =>\n this.#api<UninstallResult>(\n \"DELETE\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `PUT /servers/{server}/plugins/{bot}/{instance}/config` (moderator, field-restricted).\n * Rejects with `forbidden` (403), `invalid` + `diagnostics` (422) or `conflict` (409).\n */\n updatePluginConfig: (\n server: string,\n bot: string,\n instance: string,\n request: UpdatePluginConfigRequest,\n options?: CallOptions,\n ): Promise<WriteBackResult> =>\n this.#api<WriteBackResult>(\n \"PUT\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}/config`,\n {\n body: request,\n ...options,\n },\n ),\n /**\n * `PUT /servers/{server}/assets/{kind}` (admin) — uploads the server icon, banner or\n * splash (PNG, JPEG, GIF, WebP ≤ 8 MiB) into the repository and points\n * `spec.profile.<kind>` at it. Rejects with `unsupported_media_type` (415),\n * `too_large` (413) or `conflict` (409, when `revision` is stale).\n */\n uploadServerAsset: (\n server: string,\n kind: ServerAssetKind,\n image: Blob | ArrayBuffer | Uint8Array,\n options: CallOptions & { revision?: string } = {},\n ): Promise<ServerAssetResult> => {\n const { revision, ...rest } = options;\n return this.#api<ServerAssetResult>(\"PUT\", `/servers/${seg(server)}/assets/${seg(kind)}`, {\n body: image,\n contentType: image instanceof Blob && image.type ? image.type : \"application/octet-stream\",\n ...(revision ? { query: { revision } } : {}),\n ...rest,\n });\n },\n /** URL of the image declared in `spec.profile.<kind>` (moderator), for previews. */\n serverAssetUrl: (server: string, kind: ServerAssetKind): string =>\n this.url(`${this.apiPath}/servers/${seg(server)}/assets/${seg(kind)}`),\n };\n\n // ─────────────────────────────────────────────────────────── analytics\n\n /**\n * Server activity analytics (moderator and admin of the server). Times are UTC. Every call\n * rejects with `analytics_disabled` (404) when the runtime has no analytics store.\n */\n readonly analytics = {\n /**\n * `GET /servers/{server}/analytics/summary?period=` or `?from=&to=`: headline numbers\n * compared with the previous period of the same length, rankings and the weekday × hour\n * heatmap. `query` is a preset period (`\"30d\"`, `{ period: \"30d\" }`) or a custom range\n * (`{ from, to }`, RFC 3339 or Dates). Rejects with `invalid` (400) for a range shorter\n * than an hour, longer than 400 days or starting in the future.\n */\n summary: (\n server: string,\n query: AnalyticsSummaryQuery = \"30d\",\n options?: CallOptions,\n ): Promise<AnalyticsSummary> =>\n this.#api<AnalyticsSummary>(\"GET\", `/servers/${seg(server)}/analytics/summary`, {\n query:\n typeof query === \"string\"\n ? { period: query }\n : \"period\" in query\n ? { period: query.period }\n : { from: rfc3339(query.from), to: rfc3339(query.to) },\n ...options,\n }),\n /**\n * `GET /servers/{server}/analytics/series?metrics=&from=&to=&step=[&dim=][&top=]`. Rejects\n * with `invalid` (400) for an unknown metric or step, more than 400 days or more than 2000\n * points per series.\n */\n series: (\n server: string,\n params: AnalyticsSeriesParams,\n options?: CallOptions,\n ): Promise<AnalyticsSeries> =>\n this.#api<AnalyticsSeries>(\"GET\", `/servers/${seg(server)}/analytics/series`, {\n query: {\n metrics: params.metrics.join(\",\"),\n from: rfc3339(params.from),\n to: rfc3339(params.to),\n step: params.step,\n dim: params.dim,\n top: params.top,\n },\n ...options,\n }),\n /** `GET /servers/{server}/analytics/catalog`: every metric and whether it is collected. */\n catalog: (server: string, options?: CallOptions): Promise<AnalyticsCatalog> =>\n this.#api<AnalyticsCatalog>(\"GET\", `/servers/${seg(server)}/analytics/catalog`, options),\n };\n\n // ─────────────────────────────────────────────────────────── store (§11)\n\n readonly store = {\n /** `GET /store` (admin of a server): every source, `cicord` first, then the registries. */\n list: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"GET\", \"/store\", options)).sources,\n /**\n * `GET /store?summary=1` (admin of a server): every source with its plugin count, without\n * the plugins (`summary: false` is `list()`).\n */\n sources: async (\n { summary = true }: { summary?: boolean } = {},\n options?: CallOptions,\n ): Promise<StoreSourceSummary[]> =>\n (\n await this.#api<{ sources: StoreSourceSummary[] }>(\"GET\", \"/store\", {\n ...(summary ? { query: { summary: 1 } } : {}),\n ...options,\n })\n ).sources,\n /**\n * `GET /store/plugins` (admin of a server): one page of the plugins of every source,\n * filtered by `source`, `trust` and `installed` (default limit 50).\n */\n plugins: (params: StorePluginParams = {}, options?: CallOptions): Promise<Page<StorePlugin>> =>\n this.#api<Page<StorePlugin>>(\"GET\", \"/store/plugins\", {\n query: {\n ...pageQuery(params),\n source: params.source || undefined,\n trust: params.trust,\n installed: params.installed,\n updates: params.updates,\n },\n ...options,\n }),\n /** `POST /store/refresh` (admin of a server): refetches every registry index. */\n refresh: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"POST\", \"/store/refresh\", options)).sources,\n /**\n * `GET /store/{source}/{plugin}` (admin of a server): the latest version and what it\n * requests. Rejects with `not_found` (404) or `registry_unavailable` (502).\n */\n detail: (source: string, plugin: string, options?: CallOptions): Promise<StoreDetail> =>\n this.#api<StoreDetail>(\"GET\", `/store/${seg(source)}/${seg(plugin)}`, options),\n /**\n * `POST /servers/{server}/store/install` (admin of `server`). Rejects with `changed`,\n * `confirmation_required`, `intents`, `conflict` (409) or `invalid` + `diagnostics` (422).\n */\n install: (\n server: string,\n request: StoreInstallRequest,\n options?: CallOptions,\n ): Promise<InstallResult> =>\n this.#api<InstallResult>(\"POST\", `/servers/${seg(server)}/store/install`, {\n body: request,\n ...options,\n }),\n /**\n * `GET /store/{source}/{plugin}/update` (admin of a server): the latest version, what is\n * installed and the permission diff. Rejects with `not_installed` / `not_found` (404) or\n * `registry_unavailable` (502).\n */\n updateReview: (\n source: string,\n plugin: string,\n options?: CallOptions,\n ): Promise<StoreUpdateReview> =>\n this.#api<StoreUpdateReview>(\"GET\", `/store/${seg(source)}/${seg(plugin)}/update`, options),\n /**\n * `POST /store/{source}/{plugin}/update` (admin of every server where the plugin runs):\n * updates every instance in one write-back. Rejects with `changed`, `confirmation_required`,\n * `modified`, `up_to_date`, `intents`, `conflict` (409), `invalid` + `diagnostics` (422) or\n * `forbidden` (403, not admin on one of the servers).\n */\n update: (\n source: string,\n plugin: string,\n request: StoreUpdateRequest,\n options?: CallOptions,\n ): Promise<StoreUpdateResult> =>\n this.#api<StoreUpdateResult>(\"POST\", `/store/${seg(source)}/${seg(plugin)}/update`, {\n body: request,\n ...options,\n }),\n };\n\n readonly registries = {\n /**\n * `POST /registries` (bearer, or admin of every server): adds a registry to\n * `cicord.yaml`. Rejects with `invalid` (400 bad name / URL, 422 unreachable index) or\n * `forbidden` (403).\n */\n add: (request: AddRegistryRequest, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"POST\", \"/registries\", { body: request, ...options }),\n /** `DELETE /registries/{name}`. Rejects with `not_found` (404) or `in_use` (409). */\n remove: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}`, options),\n /**\n * `PUT /registries/{name}/token`: stores the access token of a private registry (checked\n * against its index first). Rejects with `invalid` (422, the index cannot be read with it),\n * `not_found` (404) or `unavailable` (503, no secret store).\n */\n setToken: (name: string, token: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"PUT\", `/registries/${seg(name)}/token`, {\n body: { token },\n ...options,\n }),\n /** `DELETE /registries/{name}/token`: makes the registry public again. */\n removeToken: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}/token`, options),\n };\n\n // ─────────────────────────────────────────────────────────── machine (§7)\n\n readonly machine = {\n /** `POST /api/v1/sync` — fetch the source now and sync (202). */\n sync: async (options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", \"/sync\", options);\n },\n /** `POST /api/v1/plan` with a `.tar.gz` of a repository. */\n plan: (\n archive: Blob | ArrayBuffer | Uint8Array,\n options?: CallOptions,\n ): Promise<RemotePlanResult> =>\n this.#api<RemotePlanResult>(\"POST\", \"/plan\", {\n body: archive,\n contentType: \"application/gzip\",\n ...options,\n }),\n /** `GET /healthz` → true when the process is up. */\n healthz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/healthz\", options),\n /** `GET /readyz` → true once a revision is active. */\n readyz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/readyz\", options),\n };\n\n async #probe(path: string, options?: CallOptions): Promise<boolean> {\n try {\n await this.request(\"GET\", path, {\n ...options,\n headers: { Accept: \"text/plain, application/json\" },\n });\n return true;\n } catch (error) {\n if (error instanceof CicordApiError) return false;\n throw error;\n }\n }\n\n // ─────────────────────────────────────────────────────────── simulator (§8)\n\n readonly sim = {\n /** `GET /sim/state`. */\n state: (options?: CallOptions): Promise<SimState> =>\n this.#api<SimState>(\"GET\", \"/sim/state\", options),\n /** `POST /sim/users` — creates a simulated user. */\n createUser: (username: string, options?: CallOptions): Promise<User> =>\n this.#api<User>(\"POST\", \"/sim/users\", { body: { username }, ...options }),\n /** `POST /sim/servers/{id}/members` — the user joins the server. */\n join: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", `/sim/servers/${seg(serverId)}/members`, {\n body: { userId },\n ...options,\n });\n },\n /** `DELETE /sim/servers/{id}/members/{userId}` — the user leaves. */\n leave: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\n \"DELETE\",\n `/sim/servers/${seg(serverId)}/members/${seg(userId)}`,\n options,\n );\n },\n /** `GET /sim/channels/{id}/messages?limit=` — oldest first. */\n messages: async (\n channelId: string,\n query: { limit?: number } = {},\n options?: CallOptions,\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/channels/${seg(channelId)}/messages`, {\n query,\n ...options,\n })\n ).items,\n /** `GET /sim/users/{id}/dms?limit=` — DMs received by the user from bots, oldest first. */\n dms: async (\n userId: string,\n { limit, ...options }: CallOptions & { limit?: number } = {},\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/users/${seg(userId)}/dms`, {\n query: { limit },\n ...options,\n })\n ).items,\n /** `POST /sim/messages`. */\n sendMessage: (request: SimSendMessageRequest, options?: CallOptions): Promise<Message> =>\n this.#api<Message>(\"POST\", \"/sim/messages\", { body: request, ...options }),\n /** `POST /sim/commands` — runs a slash command (waits up to 5 s for the answer). */\n command: (request: SimCommandRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/commands\", {\n body: { options: {}, ...request },\n ...options,\n }),\n /** `POST /sim/components` — clicks a button / picks select values. */\n component: (request: SimComponentRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/components\", {\n body: { values: [], ...request },\n ...options,\n }),\n /**\n * `POST /sim/modals` — submits a modal shown by a previous interaction\n * (`InteractionResult.modal`); `fields` maps text input ids to values.\n */\n modal: (request: SimModalRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/modals\", { body: request, ...options }),\n /** `GET /sim/commands?serverId=` — registered commands (all simulated servers by default). */\n commands: async (serverId?: string, options?: CallOptions): Promise<SimCommand[]> =>\n (\n await this.#api<Items<SimCommand>>(\"GET\", \"/sim/commands\", {\n query: { serverId },\n ...options,\n })\n ).items,\n /**\n * Subscribes to `GET /sim/events` (SSE). `onChange` fires for every `event: change`\n * (a hint to refresh); reconnects automatically. Call `close()` to stop.\n */\n subscribe: (\n onChange: (event: ServerSentEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/sim/events\", {\n ...options,\n onEvent: (e) => e.event === \"change\" && onChange(e),\n }),\n };\n\n /** Opens a Server-Sent Events stream on an API path (fetch-based, sends credentials/token). */\n events(path: string, options: EventStreamOptions): EventStream {\n return openEventStream(\n this.#fetch,\n this.apiUrl(path),\n {\n method: \"GET\",\n headers: this.#headers(),\n credentials: this.#credentials(),\n },\n options,\n );\n }\n}\n\nasync function readBody(response: Response): Promise<Json | string | undefined> {\n if (response.status === 204 || response.status === 205 || response.status === 304)\n return undefined;\n const text = await response.text();\n if (text === \"\") return undefined;\n const type = response.headers.get(\"Content-Type\") ?? \"\";\n if (type.includes(\"json\") || /^\\s*[[{]/.test(text)) {\n try {\n return JSON.parse(text) as Json;\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction resolveStore(store: CicordClientOptions[\"tokenStore\"], key: string): TokenStore {\n if (store && typeof store === \"object\") return store;\n if (store === \"memory\") return memoryTokenStore();\n const storage = (name: \"localStorage\" | \"sessionStorage\") => {\n try {\n return (globalThis as Record<string, unknown>)[name] as Storage | undefined;\n } catch {\n return undefined;\n }\n };\n return webStorageTokenStore(\n storage(store === \"session\" ? \"sessionStorage\" : \"localStorage\"),\n key,\n );\n}\n\nfunction globalLocation(): LocationLike | undefined {\n return typeof location === \"undefined\" ? undefined : location;\n}\n\nfunction globalHistory(): HistoryLike | undefined {\n return typeof history === \"undefined\" ? undefined : history;\n}\n\nfunction currentPath(): string | undefined {\n const loc = globalLocation();\n if (!loc) return undefined;\n const url = new URL(loc.href);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/** Creates a client. See `CicordClientOptions`. */\nexport function createCicordClient(options?: CicordClientOptions): CicordClient {\n return new CicordClient(options);\n}\n","/**\n * Contract of the `onboarding` plugin's portal routes\n * (examples/basic/plugins/onboarding — `GET /steps`, `POST /complete`).\n */\nimport type { PluginRoutes } from \"./client.ts\";\n\n/** A role a member can pick, resolved by the plugin from the server's roles. */\nexport interface OnboardingOption {\n /** Role key (servers/<server>.yaml). Used in answers. */\n role: string;\n /** Label shown in the portal (config `label`, defaults to the role name). */\n label: string;\n emoji: string;\n description: string;\n /** Discord role name and color (\"\" when the role has none). */\n name: string;\n color: string;\n}\n\nexport interface OnboardingStep {\n id: string;\n title: string;\n description: string;\n /** Several options may be selected. */\n multiple: boolean;\n /** At least one option must be selected. */\n required: boolean;\n options: OnboardingOption[];\n /** Role keys of this step the member currently has. */\n selected: string[];\n}\n\nexport interface OnboardingRole {\n key: string;\n id: string;\n name: string;\n color: string;\n}\n\n/** `GET /steps` */\nexport interface OnboardingSteps {\n title: string;\n intro: string;\n steps: OnboardingStep[];\n /** Role given when the flow is completed, if configured. */\n completedRole: OnboardingRole | null;\n completed: boolean;\n completedAt: string | null;\n}\n\n/** Answers: step id → selected role keys. */\nexport type OnboardingAnswers = Record<string, string[]>;\n\n/** `POST /complete` body. */\nexport interface OnboardingCompleteRequest {\n answers: OnboardingAnswers;\n}\n\n/** `POST /complete` response (200). Errors use the API error shape (`invalid`, 422/400). */\nexport interface OnboardingCompleteResponse {\n completed: true;\n completedAt: string;\n /** Member roles after the update. */\n roles: OnboardingRole[];\n /** Role keys added / removed by this call. */\n added: string[];\n removed: string[];\n /** Success message configured by the server. */\n message: string;\n}\n\n/** Typed wrapper over the onboarding plugin routes. */\nexport function onboardingApi(routes: PluginRoutes) {\n return {\n steps: (init?: { signal?: AbortSignal }) =>\n routes.get<OnboardingSteps>(\"/steps\", undefined, init),\n complete: (answers: OnboardingAnswers, init?: { signal?: AbortSignal }) =>\n routes.post<OnboardingCompleteResponse>(\n \"/complete\",\n { answers } satisfies OnboardingCompleteRequest,\n init,\n ),\n };\n}\n\nexport type OnboardingApi = ReturnType<typeof onboardingApi>;\n","/**\n * Contracts of the showcase plugins' portal routes (examples/showcase): `tickets` and\n * `levels`. They illustrate typing a plugin's routes on top of `client.plugin(...)`; extra\n * fields sent by a plugin are kept as is.\n */\nimport type { CallOptions, PluginRoutes } from \"./client.ts\";\n\nexport type TicketStatus = \"open\" | \"closed\";\n\nexport interface Ticket {\n /** Ticket number, as a string. */\n id: string;\n subject: string;\n status: TicketStatus;\n author: { id: string; displayName: string };\n createdAt: string;\n}\n\n/** tickets `GET /tickets` (moderator), newest first. */\nexport interface TicketList {\n items: Ticket[];\n}\n\nexport interface LeaderboardEntry {\n /** From 1. */\n rank: number;\n userId: string;\n displayName: string;\n avatarUrl: string | null;\n level: number;\n xp: number;\n}\n\n/** levels `GET /leaderboard` (public). */\nexport interface Leaderboard {\n items: LeaderboardEntry[];\n}\n\n/** Typed wrapper over the `tickets` plugin routes. */\nexport function ticketsApi(routes: PluginRoutes) {\n return {\n list: (query: { status?: TicketStatus } = {}, options?: CallOptions) =>\n routes.get<TicketList>(\"/tickets\", query, options),\n };\n}\n\n/** Typed wrapper over the `levels` plugin routes. */\nexport function levelsApi(routes: PluginRoutes) {\n return {\n leaderboard: (query: { limit?: number } = {}, options?: CallOptions) =>\n routes.get<Leaderboard>(\"/leaderboard\", query, options),\n /** levels `GET /me` (member): the viewer's own entry (shape owned by the plugin). */\n me: <T = LeaderboardEntry>(options?: CallOptions) => routes.get<T>(\"/me\", undefined, options),\n };\n}\n"],"mappings":";AAEA,MAAM,iBAA+C;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;;AAGA,SAAgB,cAAc,QAA8B;CAC1D,OAAO,eAAe,YAAY,UAAU,MAAM,aAAa,QAAQ;AACzE;;;;;AAMA,IAAa,iBAAb,MAAa,uBAAuB,MAAM;;CAExC;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;CAEA,YAAY,MAUT;EACD,MAAM,KAAK,SAAS,KAAK,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,KAAK,MAAM,CAAC;EAChF,KAAK,OAAO;EACZ,KAAK,OAAO,KAAK;EACjB,KAAK,SAAS,KAAK;E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],"sources":["../src/errors.ts","../src/routes.ts","../src/sse.ts","../src/client.ts","../src/onboarding.ts","../src/showcase.ts"],"sourcesContent":["import type { ApiErrorCode, Diagnostic, Json } from \"./types.ts\";\n\nconst CODE_BY_STATUS: Record<number, ApiErrorCode> = {\n 400: \"invalid\",\n 401: \"unauthenticated\",\n 403: \"forbidden\",\n 404: \"not_found\",\n 405: \"invalid\",\n 409: \"conflict\",\n 413: \"invalid\",\n 415: \"invalid\",\n 421: \"forbidden\",\n 422: \"invalid\",\n 500: \"internal\",\n 503: \"unavailable\",\n};\n\n/** Error code for a status when the body carries none (plain-text 404s, proxies…). */\nexport function codeForStatus(status: number): ApiErrorCode {\n return CODE_BY_STATUS[status] ?? (status >= 500 ? \"internal\" : `http_${status}`);\n}\n\n/**\n * Error raised for every non-2xx response of the runtime API (and for network failures,\n * with `status: 0` and code `\"network\"`).\n */\nexport class CicordApiError extends Error {\n /** `snake_case` error code from the body (`{\"error\": {\"code\"}}`), or derived from the status. */\n readonly code: ApiErrorCode;\n /** HTTP status, 0 for network errors. */\n readonly status: number;\n /** Validation diagnostics (422 on config updates, `POST /plan`). */\n readonly diagnostics: Diagnostic[];\n /** Parsed response body (JSON or text), when any. */\n readonly body: Json | string | undefined;\n /** How to fix it, when the runtime explains the error (plan / sync failures). */\n readonly hint: string | undefined;\n /** Raw technical text behind `message`, when the runtime explains the error. */\n readonly details: string | undefined;\n /** Humanized error code (`HumanErrorCode`), when the runtime explains the error. */\n readonly reason: string | undefined;\n\n constructor(init: {\n code: ApiErrorCode;\n status: number;\n message: string;\n diagnostics?: Diagnostic[];\n body?: Json | string;\n cause?: unknown;\n hint?: string | undefined;\n details?: string | undefined;\n reason?: string | undefined;\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = \"CicordApiError\";\n this.code = init.code;\n this.status = init.status;\n this.diagnostics = init.diagnostics ?? [];\n this.body = init.body;\n this.hint = init.hint;\n this.details = init.details;\n this.reason = init.reason;\n }\n\n /** Builds the error from a response status and its (already parsed) body. */\n static fromResponse(\n status: number,\n statusText: string,\n body: Json | string | undefined,\n ): CicordApiError {\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n const error = (body as { error?: unknown }).error;\n if (error && typeof error === \"object\" && !Array.isArray(error)) {\n const e = error as {\n code?: unknown;\n message?: unknown;\n diagnostics?: unknown;\n hint?: unknown;\n details?: unknown;\n reason?: unknown;\n };\n const str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n return new CicordApiError({\n code: typeof e.code === \"string\" && e.code ? e.code : codeForStatus(status),\n status,\n message:\n typeof e.message === \"string\" && e.message ? e.message : statusText || `HTTP ${status}`,\n diagnostics: Array.isArray(e.diagnostics) ? e.diagnostics : [],\n body,\n hint: str(e.hint),\n details: str(e.details),\n reason: str(e.reason),\n });\n }\n }\n const text = typeof body === \"string\" ? body.trim() : \"\";\n return new CicordApiError({\n code: codeForStatus(status),\n status,\n message: text && text.length <= 200 ? text : statusText || `HTTP ${status}`,\n ...(body === undefined ? {} : { body }),\n });\n }\n}\n\nexport function isCicordApiError(error: unknown, code?: ApiErrorCode): error is CicordApiError {\n return error instanceof CicordApiError && (code === undefined || error.code === code);\n}\n","/**\n * Typed plugin routes. A portal learns the routes of the plugins of its repository from\n * `src/cicord-routes.d.ts`, generated by `cicord portal typegen` (and `cicord portal build`): a\n * module augmentation of `PluginRouteRegistry`, keyed by plugin name then route key, with\n * the access level and the query, body and response types declared by the plugin's route\n * contract (plugin.yaml `spec.routes.types`).\n *\n * ```ts\n * const levels = client.routes(\"levels\", server.key, instance); // instance: { bot, instance }\n * const board = await levels.call(\"GET /leaderboard\", { query: { limit: 10 } }); // board.items…\n * const poll = await client.routes(\"polls\", server.key, p).call(\"GET /polls/:id\", { params: { id } });\n * ```\n */\nimport type { CallOptions, Query } from \"./client.ts\";\nimport type {\n OnboardingAnswers,\n OnboardingCompleteResponse,\n OnboardingSteps,\n} from \"./onboarding.ts\";\nimport type { Leaderboard, TicketList, TicketStatus } from \"./showcase.ts\";\nimport type { Json } from \"./types.ts\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n/** \"<METHOD> /path\", `:name` segments being parameters: \"GET /polls/:id\". */\nexport type RouteKey = `${RouteMethod} /${string}`;\n/** Access level of a route (`definePlugin({ routes })`). */\nexport type RouteAccess = \"public\" | \"member\" | \"moderator\" | \"admin\";\n\n/** `{ id: string }` for \"GET /polls/:id\". */\nexport type RouteParams<K extends string> = K extends `${string}/:${infer Rest}`\n ? Rest extends `${infer Name}/${infer Tail}`\n ? { [P in Name]: string } & RouteParams<`/${Tail}`>\n : { [P in Rest]: string }\n : {};\n\n/** A route whose plugin declares no types: any query and body, a JSON response. */\nexport interface UntypedRoute {\n query?: Query;\n body?: unknown;\n response: Json;\n}\n\n/**\n * One route of `PluginRouteRegistry`: its access level and, when the plugin's contract\n * `Contract` declares route `K`, its `query`, `body` and `response` (absent: `204`).\n */\nexport type RouteEntry<\n A extends RouteAccess = RouteAccess,\n Contract = {},\n K extends string = never,\n> = { readonly access: A } & ([K] extends [never]\n ? UntypedRoute\n : K extends keyof Contract\n ? Contract[K]\n : UntypedRoute);\n\n/**\n * Routes of the plugins of the repository, by plugin name then route key. Empty here:\n * `src/cicord-routes.d.ts` (generated by `cicord portal typegen`) fills it.\n */\nexport interface PluginRouteRegistry {}\n\n/** levels `GET /me`: the viewer's own standing. */\nexport interface LevelsStanding {\n userId: string;\n /** From 1, null when the viewer has no XP yet. */\n rank: number | null;\n xp: number;\n level: number;\n /** XP earned inside the current level. */\n current: number;\n /** XP needed for the next level. */\n needed: number;\n}\n\n/** polls `GET /polls/:id`. */\nexport interface PollResults {\n id: string;\n question: string;\n status: \"open\" | \"closed\";\n multiple: boolean;\n createdAt: string;\n closesAt: string;\n closedAt: string | null;\n choices: { label: string; votes: number }[];\n voters: number;\n}\n\n/**\n * Routes of the official plugins (the `cicord` source), used for a plugin that the generated\n * registry does not list: the reference portal type-checks in a repository without them.\n */\nexport interface OfficialPluginRoutes {\n levels: {\n \"GET /leaderboard\": {\n readonly access: \"public\";\n query: { limit?: number };\n response: Leaderboard;\n };\n \"GET /me\": { readonly access: \"member\"; response: LevelsStanding };\n };\n polls: { \"GET /polls/:id\": { readonly access: \"public\"; response: PollResults } };\n tickets: {\n \"GET /tickets\": {\n readonly access: \"moderator\";\n query: { status?: TicketStatus };\n response: TicketList;\n };\n \"GET /tickets/:id\": RouteEntry<\"moderator\">;\n };\n onboarding: {\n \"GET /steps\": { readonly access: \"member\"; response: OnboardingSteps };\n \"POST /complete\": {\n readonly access: \"member\";\n body: { answers: OnboardingAnswers };\n response: OnboardingCompleteResponse;\n };\n };\n}\n\n/** The routes of plugin `N`: generated registry, else official plugin, else untyped. */\nexport type RoutesOf<N extends string> = N extends keyof PluginRouteRegistry\n ? PluginRouteRegistry[N]\n : N extends keyof OfficialPluginRoutes\n ? OfficialPluginRoutes[N]\n : { [K in RouteKey]: RouteEntry };\n\n/** Route keys of plugin `N` (optionally only those of `M` methods). */\nexport type RouteKeyOf<N extends string, M extends RouteMethod = RouteMethod> = Extract<\n keyof RoutesOf<N>,\n `${M} /${string}`\n>;\n\n/** The JSON a route answers with (`undefined` for routes declaring no response: 204). */\nexport type RouteResponseOf<E> = E extends { response: infer R } ? R : undefined;\n\ntype ParamsArg<K extends string> = keyof RouteParams<K> extends never\n ? { params?: Record<string, never> }\n : { params: RouteParams<K> };\ntype QueryArg<E> = E extends { query: infer Q }\n ? {} extends Q\n ? { query?: Q }\n : { query: Q }\n : E extends { query?: infer Q }\n ? { query?: Q }\n : { query?: undefined };\ntype BodyArg<E> = E extends { body: infer B }\n ? { body: B }\n : E extends { body?: infer B }\n ? { body?: B }\n : { body?: undefined };\n\n/** What a call needs: `params` (from the key), `query` and `body` (as declared). */\nexport type RouteInput<K extends string, E> = ParamsArg<K> & QueryArg<E> & BodyArg<E>;\nexport type RouteCallOptions<K extends string, E> = RouteInput<K, E> &\n CallOptions & { headers?: Record<string, string> };\n\n/** Makes the options argument optional when nothing in it is required. */\nexport type OptionalArg<T> = {} extends T ? [options?: T] : [options: T];\n\n/** Typed calls to the routes of one instance of plugin `N`. */\nexport interface TypedPluginRoutes<N extends string> {\n readonly plugin: N;\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Calls a route: `call(\"GET /polls/:id\", { params: { id } })`. */\n call<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteCallOptions<K, RoutesOf<N>[K]>>\n ): Promise<RouteResponseOf<RoutesOf<N>[K]>>;\n /** Absolute URL of a route (`GET` routes: links, `<img src>`, EventSource…). */\n url<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteInput<K, RoutesOf<N>[K]>>\n ): string;\n}\n\n/** Splits \"GET /polls/:id\" with `{ id: \"4\" }` into `[\"GET\", \"/polls/4\"]`. */\nexport function resolveRoute(\n route: string,\n params: Record<string, string | number> | undefined = {},\n): [method: RouteMethod, path: string] {\n const space = route.indexOf(\" \");\n const method = route.slice(0, space) as RouteMethod;\n if (space < 0 || ![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method))\n throw new Error(`@cicord/client: invalid route key ${JSON.stringify(route)}`);\n const path = route\n .slice(space + 1)\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n const value = params[segment.slice(1)];\n if (value === undefined || value === \"\")\n throw new Error(`@cicord/client: missing parameter ${segment.slice(1)} of ${route}`);\n // A value taken from the page URL must never climb out of the route (\"..\": another\n // route of the instance, another plugin, another API endpoint with the viewer's\n // cookies). Dots are encoded too, so no segment can be a dot-segment; the runtime\n // reads %2E as a literal dot.\n if (value === \".\" || value === \"..\")\n throw new Error(\n `@cicord/client: invalid parameter ${segment.slice(1)} of ${route}: ${value}`,\n );\n return encodeURIComponent(String(value)).replace(/\\./g, \"%2E\");\n })\n .join(\"/\");\n return [method, path];\n}\n","/**\n * Minimal Server-Sent Events client built on fetch (not EventSource), so it can send an\n * `Authorization` header, works in Node 24 and is easy to test with a mocked fetch.\n */\n\nexport interface ServerSentEvent {\n /** Event type (`event:` field), \"message\" by default. */\n event: string;\n data: string;\n id: string;\n}\n\nexport interface EventStreamOptions {\n onEvent: (event: ServerSentEvent) => void;\n /** Called on connection errors; the stream reconnects afterwards unless closed. */\n onError?: (error: unknown) => void;\n /** Called when a connection is (re)established. */\n onOpen?: () => void;\n /** Delay before reconnecting, in ms (updated by the server's `retry:` field). Default 2000. */\n retryMs?: number;\n /** Stop after the first disconnection instead of reconnecting. */\n once?: boolean;\n /**\n * Reconnect when nothing (event or comment) arrives for this long, in ms: a proxy can\n * keep the connection open after the server went away. Use it with a server that sends\n * keep-alive comments more often (Cicord's streams: every 25 s). Default: no limit.\n */\n idleTimeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface EventStream {\n close: () => void;\n /** Resolves when the stream is closed for good. */\n readonly closed: Promise<void>;\n}\n\nexport type StreamFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/** Incremental SSE parser (https://html.spec.whatwg.org/multipage/server-sent-events.html). */\nexport class SseParser {\n #buffer = \"\";\n #data: string[] = [];\n #event = \"\";\n #lastId = \"\";\n retry: number | undefined;\n readonly #emit: (event: ServerSentEvent) => void;\n\n constructor(emit: (event: ServerSentEvent) => void) {\n this.#emit = emit;\n }\n\n push(chunk: string): void {\n this.#buffer += chunk;\n let index: number;\n while ((index = this.#buffer.search(/\\r\\n|\\r|\\n/)) >= 0) {\n const line = this.#buffer.slice(0, index);\n const sep = this.#buffer.startsWith(\"\\r\\n\", index) ? 2 : 1;\n // A lone trailing \"\\r\" might be the first half of \"\\r\\n\": wait for more input.\n if (sep === 1 && this.#buffer[index] === \"\\r\" && index === this.#buffer.length - 1) break;\n this.#buffer = this.#buffer.slice(index + sep);\n this.#line(line);\n }\n }\n\n #line(line: string): void {\n if (line === \"\") {\n if (this.#data.length > 0) {\n this.#emit({\n event: this.#event || \"message\",\n data: this.#data.join(\"\\n\"),\n id: this.#lastId,\n });\n }\n this.#data = [];\n this.#event = \"\";\n return;\n }\n if (line.startsWith(\":\")) return;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n let value = colon < 0 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n switch (field) {\n case \"data\":\n this.#data.push(value);\n break;\n case \"event\":\n this.#event = value;\n break;\n case \"id\":\n if (!value.includes(\"\\0\")) this.#lastId = value;\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) this.retry = Number(value);\n break;\n }\n }\n\n get lastEventId(): string {\n return this.#lastId;\n }\n}\n\nexport function openEventStream(\n fetcher: StreamFetch,\n url: string,\n init: RequestInit,\n options: EventStreamOptions,\n): EventStream {\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n if (options.signal?.aborted) controller.abort();\n let retryMs = options.retryMs ?? 2000;\n let lastEventId = \"\";\n\n const run = async (): Promise<void> => {\n while (!controller.signal.aborted) {\n const parser = new SseParser(options.onEvent);\n // One controller per connection: the idle watchdog ends it without closing the stream.\n const attempt = new AbortController();\n const endAttempt = (): void => attempt.abort();\n controller.signal.addEventListener(\"abort\", endAttempt, { once: true });\n let idle: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const arm = (): void => {\n if (options.idleTimeoutMs === undefined) return;\n clearTimeout(idle);\n idle = setTimeout(() => {\n timedOut = true;\n attempt.abort();\n }, options.idleTimeoutMs);\n };\n try {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n if (lastEventId) headers.set(\"Last-Event-ID\", lastEventId);\n arm();\n const response = await fetcher(url, { ...init, headers, signal: attempt.signal });\n if (!response.ok || !response.body) {\n throw new Error(`event stream ${url}: HTTP ${response.status}`);\n }\n options.onOpen?.();\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n for (;;) {\n arm();\n const { value, done } = await reader.read();\n if (done) break;\n parser.push(value);\n lastEventId = parser.lastEventId;\n if (parser.retry !== undefined) retryMs = parser.retry;\n }\n if (!controller.signal.aborted)\n options.onError?.(new Error(`event stream ${url}: disconnected`));\n } catch (error) {\n if (controller.signal.aborted) break;\n options.onError?.(\n timedOut\n ? new Error(`event stream ${url}: nothing received for ${options.idleTimeoutMs} ms`)\n : error,\n );\n } finally {\n clearTimeout(idle);\n controller.signal.removeEventListener(\"abort\", endAttempt);\n }\n if (options.once) break;\n await sleep(retryMs, controller.signal);\n }\n options.signal?.removeEventListener(\"abort\", abort);\n };\n\n const closed = run();\n return {\n close: abort,\n closed,\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n }\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n","import { CicordApiError } from \"./errors.ts\";\nimport { resolveRoute, type TypedPluginRoutes } from \"./routes.ts\";\nimport {\n openEventStream,\n type EventStream,\n type EventStreamOptions,\n type ServerSentEvent,\n} from \"./sse.ts\";\nimport type {\n AdminEvent,\n PortalAnalytics,\n PortalAnalyticsPeriod,\n AddRegistryRequest,\n AnalyticsCatalog,\n AnalyticsSeries,\n AnalyticsSeriesParams,\n AnalyticsSummary,\n AnalyticsSummaryQuery,\n AuditEntry,\n AuditQuery,\n InstallResult,\n InteractionResult,\n Items,\n Json,\n HistoryQuery,\n Me,\n Message,\n Page,\n PageParams,\n Plan,\n PluginInstance,\n PluginListParams,\n PortalMe,\n PortalServer,\n RemotePlanResult,\n RuntimeStatus,\n ServerAssetKind,\n ServerAssetResult,\n ServerDetail,\n ServerResources,\n SimCommand,\n SimCommandRequest,\n SimComponentRequest,\n SimModalRequest,\n SimSendMessageRequest,\n SimState,\n StoreDetail,\n StoreInstallRequest,\n StorePlugin,\n StorePluginParams,\n StoreSource,\n StoreSourceSummary,\n StoreUpdateRequest,\n StoreUpdateResult,\n StoreUpdateReview,\n SyncRecord,\n SyncResult,\n PauseResult,\n PauseState,\n ResumeResult,\n TokenSession,\n UninstallResult,\n UpdatePluginConfigRequest,\n User,\n WriteBackResult,\n WriteResult,\n} from \"./types.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/**\n * How browser clients authenticate (https://cicord.dev/docs/reference/http-api/authentication/):\n * - `\"cookie\"` (default): the `cicord_session` cookie, for a portal served by the runtime or\n * on a same-site origin listed in `--cors-origin`;\n * - `\"token\"`: a bearer session token kept in a `TokenStore` and sent as `Authorization`,\n * for sites embedding the SDK on another origin (cicord.yaml `spec.portal.allowedOrigins`).\n */\nexport type AuthMode = \"cookie\" | \"token\";\n\n/** A token-mode session as stored by the client. */\nexport interface StoredSession {\n token: string;\n expiresAt: string;\n}\n\n/** Where token mode keeps the session token. */\nexport interface TokenStore {\n get(): StoredSession | null;\n set(session: StoredSession | null): void;\n}\n\n/** Keeps the token in memory (lost on reload; safest against XSS persistence). */\nexport function memoryTokenStore(): TokenStore {\n let value: StoredSession | null = null;\n return { get: () => value, set: (session) => void (value = session) };\n}\n\n/** Keeps the token in `localStorage` / `sessionStorage` (falls back to memory when unavailable). */\nexport function webStorageTokenStore(\n storage: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | undefined,\n key = \"cicord:session\",\n): TokenStore {\n const memory = memoryTokenStore();\n if (!storage) return memory;\n return {\n get: () => {\n try {\n const raw = storage.getItem(key);\n const parsed = raw ? (JSON.parse(raw) as Partial<StoredSession>) : null;\n return parsed && typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"string\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : null;\n } catch {\n return memory.get();\n }\n },\n set: (session) => {\n try {\n if (session) storage.setItem(key, JSON.stringify(session));\n else storage.removeItem(key);\n } catch {\n memory.set(session);\n }\n },\n };\n}\n\n/** True for absolute http(s) URLs (links from the server config, plugin data…). */\nexport function isSafeUrl(url: string): boolean {\n try {\n const u = new URL(url);\n return u.protocol === \"https:\" || u.protocol === \"http:\";\n } catch {\n return false;\n }\n}\n\nexport interface CicordClientOptions {\n /**\n * Origin (or origin + prefix) of the Cicord runtime, e.g. \"https://cicord.example.org\".\n * Default \"\": same origin as the page.\n */\n baseUrl?: string;\n /** API prefix. Default \"/api/v1\". */\n apiPath?: string;\n /** Auth prefix (https://cicord.dev/docs/reference/http-api/authentication/). Default \"/auth\". */\n authPath?: string;\n /** fetch implementation. Default: the global `fetch`, looked up at call time. */\n fetch?: FetchLike;\n /** Bearer token (runtime token) for machine clients; a function is called per request. */\n token?: string | (() => string | undefined | null);\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /**\n * Fetch credentials mode. Default \"include\" in cookie mode (session cookie, also\n * cross-origin with CORS), \"omit\" in token mode.\n */\n credentials?: RequestCredentials;\n /** Browser auth mode. Default \"cookie\". See `AuthMode`. */\n auth?: AuthMode;\n /**\n * Token mode: where the session token lives. \"local\" (default in browsers) and\n * \"session\" use Web Storage under `storageKey`; \"memory\" forgets it on reload.\n */\n tokenStore?: TokenStore | \"local\" | \"session\" | \"memory\";\n /** Web Storage key of token mode. Default \"cicord:session:<baseUrl>\". */\n storageKey?: string;\n}\n\nexport type Query = Record<string, string | number | boolean | undefined | null>;\n\nexport interface RequestOptions {\n query?: Query;\n /** JSON-serialisable body, or a raw body (Blob, ArrayBuffer, Uint8Array, string, FormData…). */\n body?: unknown;\n /** Content type for raw bodies. */\n contentType?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface CallOptions {\n signal?: AbortSignal;\n}\n\n/** Calls to the routes of one plugin instance (https://cicord.dev/docs/reference/http-api/portal/). */\nexport interface PluginRoutes {\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Absolute URL of a route path. */\n url: (path: string, query?: Query) => string;\n request<T = Json>(method: string, path: string, options?: RequestOptions): Promise<T>;\n get<T = Json>(path: string, query?: Query, options?: CallOptions): Promise<T>;\n post<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n put<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n patch<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n delete<T = Json>(path: string, options?: CallOptions): Promise<T>;\n}\n\n/** Minimal Location / History used by the auth helpers (injectable for tests and SSR). */\nexport interface LocationLike {\n href: string;\n assign?: (url: string) => void;\n}\nexport interface HistoryLike {\n replaceState: (data: unknown, unused: string, url?: string | URL | null) => void;\n readonly state?: unknown;\n}\n\nexport interface ExchangeLinkTokenOptions {\n location?: LocationLike;\n history?: HistoryLike;\n /** Query parameter carrying the token. Default \"cicord_token\". */\n param?: string;\n /** Query parameter carrying the one-time code of a token-mode login. Default \"cicord_code\". */\n codeParam?: string;\n}\n\n/** Query parameters a login may leave in the URL (removed by `exchangeLinkToken`). */\nexport const LOGIN_PARAMS = [\"cicord_token\", \"cicord_code\"] as const;\n\nconst isRawBody = (body: unknown): boolean =>\n typeof body === \"string\" ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n (typeof Blob !== \"undefined\" && body instanceof Blob) ||\n (typeof FormData !== \"undefined\" && body instanceof FormData) ||\n (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream);\n\nconst seg = (value: string): string => encodeURIComponent(value);\n\nfunction trimSlash(value: string): string {\n // A loop, not /\\/+$/: that regex backtracks quadratically on many slashes not at the end.\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\n/** Query string of a paged list (https://cicord.dev/docs/reference/http-api/ \"Data tables\"); empty values are left out. */\nfunction pageQuery(params: PageParams = {}): Query {\n return {\n q: params.q?.trim() || undefined,\n sort: params.sort || undefined,\n order: params.order,\n offset: params.offset,\n limit: params.limit,\n };\n}\n\n/** A Date as RFC 3339 UTC without milliseconds (strings pass through). */\nfunction rfc3339(value: Date | string | undefined): string | undefined {\n if (value === undefined || typeof value === \"string\") return value;\n return value.toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\nfunction withQuery(url: string, query?: Query): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${qs}` : url;\n}\n\n/**\n * Typed client for the Cicord runtime HTTP API v1 (https://cicord.dev/docs/reference/http-api/). Framework-agnostic: works in\n * browsers, Node 24, workers. Every non-2xx response rejects with `CicordApiError`.\n */\nexport class CicordClient {\n readonly baseUrl: string;\n readonly apiPath: string;\n readonly authPath: string;\n readonly authMode: AuthMode;\n readonly #options: CicordClientOptions;\n readonly #store: TokenStore;\n readonly #listeners = new Set<() => void>();\n #pendingLink: Promise<Me> | undefined;\n\n constructor(options: CicordClientOptions = {}) {\n this.#options = options;\n this.baseUrl = trimSlash(options.baseUrl ?? \"\");\n this.apiPath = trimSlash(options.apiPath ?? \"/api/v1\");\n this.authPath = trimSlash(options.authPath ?? \"/auth\");\n this.authMode = options.auth ?? \"cookie\";\n this.#store = resolveStore(\n options.tokenStore,\n options.storageKey ?? `cicord:session:${this.baseUrl}`,\n );\n }\n\n // ─────────────────────────────────────────────────────────── token-mode session\n\n /** The token-mode session, or null (cookie mode, logged out or expired). */\n session(): StoredSession | null {\n if (this.authMode !== \"token\") return null;\n const s = this.#store.get();\n if (s && Date.parse(s.expiresAt) <= Date.now()) {\n this.#setSession(null);\n return null;\n }\n return s;\n }\n\n /** Called when the token-mode session changes (login, logout, expiry, revocation). */\n onSessionChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n #setSession(session: StoredSession | null): void {\n this.#store.set(session);\n for (const listener of this.#listeners) listener();\n }\n\n #adopt(session: TokenSession): Me {\n this.#setSession({ token: session.token, expiresAt: session.expiresAt });\n return session.me;\n }\n\n // ─────────────────────────────────────────────────────────── transport\n\n /** Absolute URL of a path relative to the runtime origin (e.g. \"/api/v1/me\"). */\n url(path: string, query?: Query): string {\n return withQuery(`${this.baseUrl}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n /** URL of an API path (e.g. \"/me\" → \"/api/v1/me\"). */\n apiUrl(path: string, query?: Query): string {\n return this.url(`${this.apiPath}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n #headers(extra?: Record<string, string>): Headers {\n const headers = new Headers(this.#options.headers);\n // CSRF protection (https://cicord.dev/docs/reference/http-api/authentication/): the runtime rejects cookie-authenticated\n // state-changing requests without this header.\n headers.set(\"X-Cicord-Request\", \"1\");\n const token =\n (typeof this.#options.token === \"function\" ? this.#options.token() : this.#options.token) ??\n this.session()?.token;\n if (token) headers.set(\"Authorization\", `Bearer ${token}`);\n for (const [k, v] of Object.entries(extra ?? {})) headers.set(k, v);\n return headers;\n }\n\n #fetch: FetchLike = (input, init) => {\n const impl = this.#options.fetch ?? globalThis.fetch;\n if (!impl) throw new Error(\"@cicord/client: no fetch implementation available\");\n return impl(input, init);\n };\n\n /** Sends a request to an absolute runtime path (no API prefix added). */\n async request<T = Json>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const headers = this.#headers(options.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n if (isRawBody(options.body)) {\n body = options.body as BodyInit;\n if (options.contentType) headers.set(\"Content-Type\", options.contentType);\n } else {\n body = JSON.stringify(options.body);\n headers.set(\"Content-Type\", options.contentType ?? \"application/json\");\n }\n }\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n credentials: this.#credentials(),\n ...(body === undefined ? {} : { body }),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n\n let response: Response;\n try {\n response = await this.#fetch(this.url(path, options.query), init);\n } catch (cause) {\n if (options.signal?.aborted) throw cause;\n throw new CicordApiError({\n code: \"network\",\n status: 0,\n message: cause instanceof Error ? cause.message : \"network error\",\n cause,\n });\n }\n\n const parsed = await readBody(response);\n if (!response.ok) {\n // A revoked or expired token: forget it so the app shows the logged-out state.\n if (response.status === 401 && this.session()?.token && !this.#options.token)\n this.#setSession(null);\n throw CicordApiError.fromResponse(response.status, response.statusText, parsed);\n }\n return parsed as T;\n }\n\n #credentials(): RequestCredentials {\n return this.#options.credentials ?? (this.authMode === \"token\" ? \"omit\" : \"include\");\n }\n\n #api<T>(method: string, path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(method, `${this.apiPath}${path}`, options);\n }\n\n // ─────────────────────────────────────────────────────────── me & auth (§1, §2)\n\n /** `GET /api/v1/me`. Rejects with code `unauthenticated` when there is no session. */\n me(options?: CallOptions): Promise<Me> {\n return this.#api<Me>(\"GET\", \"/me\", options);\n }\n\n /** Like `me()`, but resolves `null` instead of rejecting when not logged in. */\n async meOrNull(options?: CallOptions): Promise<Me | null> {\n try {\n return await this.me(options);\n } catch (error) {\n if (error instanceof CicordApiError && error.code === \"unauthenticated\") return null;\n throw error;\n }\n }\n\n readonly auth = {\n /**\n * URL that starts the Discord OAuth2 login and comes back to `redirect` (a path on the\n * portal; default: the current page).\n */\n loginUrl: (redirect?: string): string => {\n if (this.authMode === \"token\") {\n // The runtime redirects back with ?cicord_code=… to this absolute URL, which must be\n // on an allowed origin (spec.portal.allowedOrigins or --cors-origin).\n const here = globalLocation()?.href;\n const target =\n redirect !== undefined && here ? new URL(redirect, here).toString() : (redirect ?? here);\n return this.url(`${this.authPath}/login`, { mode: \"token\", redirect: target });\n }\n const target = redirect ?? currentPath();\n return this.url(`${this.authPath}/login`, target ? { redirect: target } : undefined);\n },\n\n /** Navigates the browser to the login URL. */\n login: (redirect?: string, location: LocationLike | undefined = globalLocation()): void => {\n const url = this.auth.loginUrl(redirect);\n if (location?.assign) location.assign(url);\n else if (location) location.href = url;\n else throw new Error(\"@cicord/client: auth.login() needs a browser location\");\n },\n\n /** `POST /auth/link` with an explicit token (stores the session token in token mode). */\n link: async (token: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/link`, { body: { token }, ...options });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/link`, {\n body: { token, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** Token mode: `POST /auth/token` — redeems the one-time code of an OAuth login. */\n redeem: async (code: string, options?: CallOptions): Promise<Me> =>\n this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/token`, {\n body: { code },\n ...options,\n }),\n ),\n\n /**\n * Reads `cicord_token` from the current URL (a signed link from `ctx.portal.link()`),\n * removes it from the address bar right away (so it is neither bookmarked nor sent twice),\n * and exchanges it for a session. Resolves `null` when the URL has no token.\n * Calls made while an exchange is in flight share it (safe under React StrictMode).\n */\n exchangeLinkToken: (options: ExchangeLinkTokenOptions = {}): Promise<Me | null> => {\n const location = options.location ?? globalLocation();\n const param = options.param ?? \"cicord_token\";\n const codeParam = options.codeParam ?? \"cicord_code\";\n if (!location) return Promise.resolve(null);\n const url = new URL(location.href);\n const token = url.searchParams.get(param);\n // A token-mode OAuth login comes back with a one-time code.\n const code = this.authMode === \"token\" ? url.searchParams.get(codeParam) : null;\n if (!token && !code) return this.#pendingLink ?? Promise.resolve(null);\n\n url.searchParams.delete(param);\n url.searchParams.delete(codeParam);\n const history = options.history ?? globalHistory();\n const clean = `${url.pathname}${url.search}${url.hash}`;\n if (history) history.replaceState(history.state ?? null, \"\", clean);\n else location.href = url.toString();\n\n const exchange = token ? this.auth.link(token) : this.auth.redeem(code as string);\n const pending = exchange.finally(() => {\n if (this.#pendingLink === pending) this.#pendingLink = undefined;\n });\n this.#pendingLink = pending;\n return pending;\n },\n\n /** `POST /auth/dev-login` — `cicord dev` only (stores the session token in token mode). */\n devLogin: async (userId: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId },\n ...options,\n });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** `POST /auth/logout` (token mode: revokes the token and forgets it). */\n logout: async (options?: CallOptions): Promise<void> => {\n try {\n await this.request<void>(\"POST\", `${this.authPath}/logout`, options);\n } finally {\n if (this.authMode === \"token\") this.#setSession(null);\n }\n },\n };\n\n // ─────────────────────────────────────────────────────────── portal (§6)\n\n readonly portal = {\n /** `GET /portal/servers` — servers with a portal. */\n servers: async (options?: CallOptions): Promise<PortalServer[]> =>\n (await this.#api<Items<PortalServer>>(\"GET\", \"/portal/servers\", options)).items.map((s) =>\n this.#absolutize(s),\n ),\n /** `GET /portal/{server}`. */\n server: async (server: string, options?: CallOptions): Promise<PortalServer> =>\n this.#absolutize(await this.#api<PortalServer>(\"GET\", `/portal/${seg(server)}`, options)),\n /** `GET /portal/{server}/me` — the viewer as a member of the server. */\n me: (server: string, options?: CallOptions): Promise<PortalMe> =>\n this.#api<PortalMe>(\"GET\", `/portal/${seg(server)}/me`, options),\n /**\n * `GET /portal/{server}/analytics?period=` — server-wide activity for the portal, when\n * the server opts in (`spec.analytics.portal`: members or public; 404 otherwise).\n */\n analytics: (\n server: string,\n period: PortalAnalyticsPeriod = \"30d\",\n options?: CallOptions,\n ): Promise<PortalAnalytics> =>\n this.#api<PortalAnalytics>(\"GET\", `/portal/${seg(server)}/analytics`, {\n query: { period },\n ...options,\n }),\n };\n\n /** Runtime-relative image URLs (logo, banner) resolved against `baseUrl` (embedded portals). */\n #absolutize(server: PortalServer): PortalServer {\n if (!this.baseUrl) return server;\n const abs = (u: string | undefined) => (u && u.startsWith(\"/\") ? this.url(u) : u);\n return {\n ...server,\n theme: { ...server.theme, logo: abs(server.theme.logo) ?? \"\" },\n banner: abs(server.banner) ?? \"\",\n };\n }\n\n /** Routes of a plugin instance: `/api/v1/portal/{server}/plugins/{bot}/{instance}/{path}`. */\n plugin(server: string, bot: string, instance: string): PluginRoutes {\n const prefix = `${this.apiPath}/portal/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`;\n const full = (path: string): string => `${prefix}${path.startsWith(\"/\") ? path : `/${path}`}`;\n const request = <T = Json>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T> => this.request<T>(method, full(path), options);\n const withBody =\n (method: string) =>\n <T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T> =>\n request<T>(method, path, { ...options, ...(body === undefined ? {} : { body }) });\n return {\n server,\n bot,\n instance,\n url: (path, query) => this.url(full(path), query),\n request,\n get: <T = Json>(path: string, query?: Query, options?: CallOptions) =>\n request<T>(\"GET\", path, { ...options, ...(query ? { query } : {}) }),\n post: withBody(\"POST\"),\n put: withBody(\"PUT\"),\n patch: withBody(\"PATCH\"),\n delete: <T = Json>(path: string, options?: CallOptions) =>\n request<T>(\"DELETE\", path, options),\n };\n }\n\n /**\n * Typed calls to the routes of an instance of plugin `plugin` (types from the generated\n * `src/cicord-routes.d.ts`, see `PluginRouteRegistry`). `at` is the instance, typically\n * found in `PortalServer.plugins` by plugin name.\n */\n routes<N extends string>(\n plugin: N,\n server: string,\n at: { bot: string; instance: string },\n ): TypedPluginRoutes<N> {\n const routes = this.plugin(server, at.bot, at.instance);\n type Loose = { params?: Record<string, string>; query?: object; body?: unknown };\n return {\n plugin,\n server,\n bot: at.bot,\n instance: at.instance,\n // async: an invalid parameter rejects like any failed call.\n call: (async (route: string, options: Loose & RequestOptions = {}) => {\n const { params, query, body, ...rest } = options;\n const [method, path] = resolveRoute(route, params);\n return routes.request(method, path, {\n ...rest,\n ...(query ? { query } : {}),\n ...(body === undefined ? {} : { body }),\n });\n }) as TypedPluginRoutes<N>[\"call\"],\n url: ((route: string, options: Loose = {}) => {\n const [, path] = resolveRoute(route, options.params);\n return routes.url(path, options.query as Query | undefined);\n }) as TypedPluginRoutes<N>[\"url\"],\n };\n }\n\n // ─────────────────────────────────────────────────────────── admin (§3–§5)\n\n readonly admin = {\n /**\n * Subscribes to `GET /events` (SSE, moderator): `hello` on every (re)connection, then\n * change hints for the runtime (`status`) and the servers you moderate (`sync`,\n * `plugins`, `analytics`). Reconnects automatically; call `close()` to stop.\n */\n subscribe: (\n onEvent: (event: AdminEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/events\", {\n ...options,\n onEvent: (e) => {\n let data: Record<string, unknown> = {};\n try {\n data = JSON.parse(e.data || \"{}\") as Record<string, unknown>;\n } catch {\n return;\n }\n const server = typeof data.server === \"string\" ? data.server : undefined;\n switch (e.event) {\n case \"hello\":\n onEvent({\n type: \"hello\",\n version: typeof data.version === \"string\" ? data.version : \"\",\n revision: typeof data.revision === \"string\" ? data.revision : \"\",\n });\n break;\n case \"status\":\n case \"stopping\":\n case \"store\":\n onEvent({ type: e.event });\n break;\n case \"sync\":\n case \"plugins\":\n case \"analytics\":\n onEvent(server === undefined ? { type: e.event } : { type: e.event, server });\n break;\n }\n },\n }),\n /** `GET /status` (admin, moderator) — visible servers only. */\n status: (options?: CallOptions): Promise<RuntimeStatus> =>\n this.#api<RuntimeStatus>(\"GET\", \"/status\", options),\n /** `GET /history?limit=&target=` (admin, moderator), newest first. */\n history: async (query: HistoryQuery = {}, options?: CallOptions): Promise<SyncRecord[]> =>\n (\n await this.#api<Items<SyncRecord>>(\"GET\", \"/history\", {\n query: { limit: query.limit, target: query.target },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}` (moderator). */\n server: (server: string, options?: CallOptions): Promise<ServerDetail> =>\n this.#api<ServerDetail>(\"GET\", `/servers/${seg(server)}`, options),\n /** `GET /servers/{server}/resources` (moderator) — roles, categories, channels for pickers. */\n resources: (server: string, options?: CallOptions): Promise<ServerResources> =>\n this.#api<ServerResources>(\"GET\", `/servers/${seg(server)}/resources`, options),\n /** `GET /servers/{server}/plan` (admin). */\n plan: (server: string, options?: CallOptions): Promise<Plan> =>\n this.#api<Plan>(\"GET\", `/servers/${seg(server)}/plan`, options),\n /**\n * `POST /servers/{server}/sync` (admin) — reconcile now. Rejects with `paused` (409)\n * while enforcement is paused, unless `resume` is set (resumes, then syncs).\n */\n sync: (\n server: string,\n options: CallOptions & { resume?: boolean } = {},\n ): Promise<SyncResult> => {\n const { resume, ...rest } = options;\n return this.#api<SyncResult>(\"POST\", `/servers/${seg(server)}/sync`, {\n ...rest,\n ...(resume ? { body: { resume: true } } : {}),\n });\n },\n /** `GET /servers/{server}/pause` (moderator) — the pause and the pending plan. */\n pauseState: (server: string, options?: CallOptions): Promise<PauseState> =>\n this.#api<PauseState>(\"GET\", `/servers/${seg(server)}/pause`, options),\n /**\n * `POST /servers/{server}/pause` (moderator) — pauses enforcement: nothing is applied to\n * the server until it is resumed.\n */\n pause: (\n server: string,\n body: { reason?: string } = {},\n options?: CallOptions,\n ): Promise<PauseResult> =>\n this.#api<PauseResult>(\"POST\", `/servers/${seg(server)}/pause`, { ...options, body }),\n /** `POST /servers/{server}/resume` (moderator) — the next revision or sync applies again. */\n resume: (server: string, options?: CallOptions): Promise<ResumeResult> =>\n this.#api<ResumeResult>(\"POST\", `/servers/${seg(server)}/resume`, options),\n /** `GET /servers/{server}/audit?before=&limit=` (moderator), newest first. */\n audit: async (\n server: string,\n query: AuditQuery = {},\n options?: CallOptions,\n ): Promise<AuditEntry[]> =>\n (\n await this.#api<Items<AuditEntry>>(\"GET\", `/servers/${seg(server)}/audit`, {\n query: { before: query.before, limit: query.limit },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}/plugins` (moderator): every instance. */\n plugins: async (server: string, options?: CallOptions): Promise<PluginInstance[]> =>\n (await this.#api<Items<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, options))\n .items,\n /**\n * `GET /servers/{server}/plugins?q&sort&order&offset&limit` (moderator): one page of\n * instances. Without `limit` the page holds every instance. Rejects with `invalid` (400)\n * on an unknown sort key.\n */\n pluginsPage: (\n server: string,\n params: PluginListParams = {},\n options?: CallOptions,\n ): Promise<Page<PluginInstance>> =>\n this.#api<Page<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, {\n query: { ...pageQuery(params), updates: params.updates },\n ...options,\n }),\n /** `GET /servers/{server}/plugins/{bot}/{instance}` (moderator). Rejects with `not_found`. */\n plugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<PluginInstance> =>\n this.#api<PluginInstance>(\n \"GET\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `DELETE /servers/{server}/plugins/{bot}/{instance}` (admin): uninstalls the instance from\n * the server (plugin data is kept). Rejects with `invalid` + `diagnostics` (422, something\n * depends on it), `conflict` (409), `forbidden` (403) or `not_found` (404).\n */\n uninstallPlugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<UninstallResult> =>\n this.#api<UninstallResult>(\n \"DELETE\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `PUT /servers/{server}/plugins/{bot}/{instance}/config` (moderator, field-restricted).\n * Rejects with `forbidden` (403), `invalid` + `diagnostics` (422) or `conflict` (409).\n */\n updatePluginConfig: (\n server: string,\n bot: string,\n instance: string,\n request: UpdatePluginConfigRequest,\n options?: CallOptions,\n ): Promise<WriteBackResult> =>\n this.#api<WriteBackResult>(\n \"PUT\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}/config`,\n {\n body: request,\n ...options,\n },\n ),\n /**\n * `PUT /servers/{server}/assets/{kind}` (admin) — uploads the server icon, banner or\n * splash (PNG, JPEG, GIF, WebP ≤ 8 MiB) into the repository and points\n * `spec.profile.<kind>` at it. Rejects with `unsupported_media_type` (415),\n * `too_large` (413) or `conflict` (409, when `revision` is stale).\n */\n uploadServerAsset: (\n server: string,\n kind: ServerAssetKind,\n image: Blob | ArrayBuffer | Uint8Array,\n options: CallOptions & { revision?: string } = {},\n ): Promise<ServerAssetResult> => {\n const { revision, ...rest } = options;\n return this.#api<ServerAssetResult>(\"PUT\", `/servers/${seg(server)}/assets/${seg(kind)}`, {\n body: image,\n contentType: image instanceof Blob && image.type ? image.type : \"application/octet-stream\",\n ...(revision ? { query: { revision } } : {}),\n ...rest,\n });\n },\n /** URL of the image declared in `spec.profile.<kind>` (moderator), for previews. */\n serverAssetUrl: (server: string, kind: ServerAssetKind): string =>\n this.url(`${this.apiPath}/servers/${seg(server)}/assets/${seg(kind)}`),\n };\n\n // ─────────────────────────────────────────────────────────── analytics\n\n /**\n * Server activity analytics (moderator and admin of the server). Times are UTC. Every call\n * rejects with `analytics_disabled` (404) when the runtime has no analytics store.\n */\n readonly analytics = {\n /**\n * `GET /servers/{server}/analytics/summary?period=` or `?from=&to=`: headline numbers\n * compared with the previous period of the same length, rankings and the weekday × hour\n * heatmap. `query` is a preset period (`\"30d\"`, `{ period: \"30d\" }`) or a custom range\n * (`{ from, to }`, RFC 3339 or Dates). Rejects with `invalid` (400) for a range shorter\n * than an hour, longer than 400 days or starting in the future.\n */\n summary: (\n server: string,\n query: AnalyticsSummaryQuery = \"30d\",\n options?: CallOptions,\n ): Promise<AnalyticsSummary> =>\n this.#api<AnalyticsSummary>(\"GET\", `/servers/${seg(server)}/analytics/summary`, {\n query:\n typeof query === \"string\"\n ? { period: query }\n : \"period\" in query\n ? { period: query.period }\n : { from: rfc3339(query.from), to: rfc3339(query.to) },\n ...options,\n }),\n /**\n * `GET /servers/{server}/analytics/series?metrics=&from=&to=&step=[&dim=][&top=]`. Rejects\n * with `invalid` (400) for an unknown metric or step, more than 400 days or more than 2000\n * points per series.\n */\n series: (\n server: string,\n params: AnalyticsSeriesParams,\n options?: CallOptions,\n ): Promise<AnalyticsSeries> =>\n this.#api<AnalyticsSeries>(\"GET\", `/servers/${seg(server)}/analytics/series`, {\n query: {\n metrics: params.metrics.join(\",\"),\n from: rfc3339(params.from),\n to: rfc3339(params.to),\n step: params.step,\n dim: params.dim,\n top: params.top,\n },\n ...options,\n }),\n /** `GET /servers/{server}/analytics/catalog`: every metric and whether it is collected. */\n catalog: (server: string, options?: CallOptions): Promise<AnalyticsCatalog> =>\n this.#api<AnalyticsCatalog>(\"GET\", `/servers/${seg(server)}/analytics/catalog`, options),\n };\n\n // ─────────────────────────────────────────────────────────── store (§11)\n\n readonly store = {\n /** `GET /store` (admin of a server): every source, `cicord` first, then the registries. */\n list: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"GET\", \"/store\", options)).sources,\n /**\n * `GET /store?summary=1` (admin of a server): every source with its plugin count, without\n * the plugins (`summary: false` is `list()`).\n */\n sources: async (\n { summary = true }: { summary?: boolean } = {},\n options?: CallOptions,\n ): Promise<StoreSourceSummary[]> =>\n (\n await this.#api<{ sources: StoreSourceSummary[] }>(\"GET\", \"/store\", {\n ...(summary ? { query: { summary: 1 } } : {}),\n ...options,\n })\n ).sources,\n /**\n * `GET /store/plugins` (admin of a server): one page of the plugins of every source,\n * filtered by `source`, `trust` and `installed` (default limit 50).\n */\n plugins: (params: StorePluginParams = {}, options?: CallOptions): Promise<Page<StorePlugin>> =>\n this.#api<Page<StorePlugin>>(\"GET\", \"/store/plugins\", {\n query: {\n ...pageQuery(params),\n source: params.source || undefined,\n trust: params.trust,\n installed: params.installed,\n updates: params.updates,\n },\n ...options,\n }),\n /** `POST /store/refresh` (admin of a server): refetches every registry index. */\n refresh: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"POST\", \"/store/refresh\", options)).sources,\n /**\n * `GET /store/{source}/{plugin}` (admin of a server): the latest version and what it\n * requests. Rejects with `not_found` (404) or `registry_unavailable` (502).\n */\n detail: (source: string, plugin: string, options?: CallOptions): Promise<StoreDetail> =>\n this.#api<StoreDetail>(\"GET\", `/store/${seg(source)}/${seg(plugin)}`, options),\n /**\n * `POST /servers/{server}/store/install` (admin of `server`). Rejects with `changed`,\n * `confirmation_required`, `intents`, `conflict` (409) or `invalid` + `diagnostics` (422).\n */\n install: (\n server: string,\n request: StoreInstallRequest,\n options?: CallOptions,\n ): Promise<InstallResult> =>\n this.#api<InstallResult>(\"POST\", `/servers/${seg(server)}/store/install`, {\n body: request,\n ...options,\n }),\n /**\n * `GET /store/{source}/{plugin}/update` (admin of a server): the latest version, what is\n * installed and the permission diff. Rejects with `not_installed` / `not_found` (404) or\n * `registry_unavailable` (502).\n */\n updateReview: (\n source: string,\n plugin: string,\n options?: CallOptions,\n ): Promise<StoreUpdateReview> =>\n this.#api<StoreUpdateReview>(\"GET\", `/store/${seg(source)}/${seg(plugin)}/update`, options),\n /**\n * `POST /store/{source}/{plugin}/update` (admin of every server where the plugin runs):\n * updates every instance in one write-back. Rejects with `changed`, `confirmation_required`,\n * `modified`, `up_to_date`, `intents`, `conflict` (409), `invalid` + `diagnostics` (422) or\n * `forbidden` (403, not admin on one of the servers).\n */\n update: (\n source: string,\n plugin: string,\n request: StoreUpdateRequest,\n options?: CallOptions,\n ): Promise<StoreUpdateResult> =>\n this.#api<StoreUpdateResult>(\"POST\", `/store/${seg(source)}/${seg(plugin)}/update`, {\n body: request,\n ...options,\n }),\n };\n\n readonly registries = {\n /**\n * `POST /registries` (bearer, or admin of every server): adds a registry to\n * `cicord.yaml`. Rejects with `invalid` (400 bad name / URL, 422 unreachable index) or\n * `forbidden` (403).\n */\n add: (request: AddRegistryRequest, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"POST\", \"/registries\", { body: request, ...options }),\n /** `DELETE /registries/{name}`. Rejects with `not_found` (404) or `in_use` (409). */\n remove: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}`, options),\n /**\n * `PUT /registries/{name}/token`: stores the access token of a private registry (checked\n * against its index first). Rejects with `invalid` (422, the index cannot be read with it),\n * `not_found` (404) or `unavailable` (503, no secret store).\n */\n setToken: (name: string, token: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"PUT\", `/registries/${seg(name)}/token`, {\n body: { token },\n ...options,\n }),\n /** `DELETE /registries/{name}/token`: makes the registry public again. */\n removeToken: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}/token`, options),\n };\n\n // ─────────────────────────────────────────────────────────── machine (§7)\n\n readonly machine = {\n /** `POST /api/v1/sync` — fetch the source now and sync (202). */\n sync: async (options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", \"/sync\", options);\n },\n /** `POST /api/v1/plan` with a `.tar.gz` of a repository. */\n plan: (\n archive: Blob | ArrayBuffer | Uint8Array,\n options?: CallOptions,\n ): Promise<RemotePlanResult> =>\n this.#api<RemotePlanResult>(\"POST\", \"/plan\", {\n body: archive,\n contentType: \"application/gzip\",\n ...options,\n }),\n /** `GET /healthz` → true when the process is up. */\n healthz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/healthz\", options),\n /** `GET /readyz` → true once a revision is active. */\n readyz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/readyz\", options),\n };\n\n async #probe(path: string, options?: CallOptions): Promise<boolean> {\n try {\n await this.request(\"GET\", path, {\n ...options,\n headers: { Accept: \"text/plain, application/json\" },\n });\n return true;\n } catch (error) {\n if (error instanceof CicordApiError) return false;\n throw error;\n }\n }\n\n // ─────────────────────────────────────────────────────────── simulator (§8)\n\n readonly sim = {\n /** `GET /sim/state`. */\n state: (options?: CallOptions): Promise<SimState> =>\n this.#api<SimState>(\"GET\", \"/sim/state\", options),\n /** `POST /sim/users` — creates a simulated user. */\n createUser: (username: string, options?: CallOptions): Promise<User> =>\n this.#api<User>(\"POST\", \"/sim/users\", { body: { username }, ...options }),\n /** `POST /sim/servers/{id}/members` — the user joins the server. */\n join: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", `/sim/servers/${seg(serverId)}/members`, {\n body: { userId },\n ...options,\n });\n },\n /** `DELETE /sim/servers/{id}/members/{userId}` — the user leaves. */\n leave: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\n \"DELETE\",\n `/sim/servers/${seg(serverId)}/members/${seg(userId)}`,\n options,\n );\n },\n /** `GET /sim/channels/{id}/messages?limit=` — oldest first. */\n messages: async (\n channelId: string,\n query: { limit?: number } = {},\n options?: CallOptions,\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/channels/${seg(channelId)}/messages`, {\n query,\n ...options,\n })\n ).items,\n /** `GET /sim/users/{id}/dms?limit=` — DMs received by the user from bots, oldest first. */\n dms: async (\n userId: string,\n { limit, ...options }: CallOptions & { limit?: number } = {},\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/users/${seg(userId)}/dms`, {\n query: { limit },\n ...options,\n })\n ).items,\n /** `POST /sim/messages`. */\n sendMessage: (request: SimSendMessageRequest, options?: CallOptions): Promise<Message> =>\n this.#api<Message>(\"POST\", \"/sim/messages\", { body: request, ...options }),\n /** `POST /sim/commands` — runs a slash command (waits up to 5 s for the answer). */\n command: (request: SimCommandRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/commands\", {\n body: { options: {}, ...request },\n ...options,\n }),\n /** `POST /sim/components` — clicks a button / picks select values. */\n component: (request: SimComponentRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/components\", {\n body: { values: [], ...request },\n ...options,\n }),\n /**\n * `POST /sim/modals` — submits a modal shown by a previous interaction\n * (`InteractionResult.modal`); `fields` maps text input ids to values.\n */\n modal: (request: SimModalRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/modals\", { body: request, ...options }),\n /** `GET /sim/commands?serverId=` — registered commands (all simulated servers by default). */\n commands: async (serverId?: string, options?: CallOptions): Promise<SimCommand[]> =>\n (\n await this.#api<Items<SimCommand>>(\"GET\", \"/sim/commands\", {\n query: { serverId },\n ...options,\n })\n ).items,\n /**\n * Subscribes to `GET /sim/events` (SSE). `onChange` fires for every `event: change`\n * (a hint to refresh); reconnects automatically. Call `close()` to stop.\n */\n subscribe: (\n onChange: (event: ServerSentEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/sim/events\", {\n ...options,\n onEvent: (e) => e.event === \"change\" && onChange(e),\n }),\n };\n\n /** Opens a Server-Sent Events stream on an API path (fetch-based, sends credentials/token). */\n events(path: string, options: EventStreamOptions): EventStream {\n return openEventStream(\n this.#fetch,\n this.apiUrl(path),\n {\n method: \"GET\",\n headers: this.#headers(),\n credentials: this.#credentials(),\n },\n options,\n );\n }\n}\n\nasync function readBody(response: Response): Promise<Json | string | undefined> {\n if (response.status === 204 || response.status === 205 || response.status === 304)\n return undefined;\n const text = await response.text();\n if (text === \"\") return undefined;\n const type = response.headers.get(\"Content-Type\") ?? \"\";\n if (type.includes(\"json\") || /^\\s*[[{]/.test(text)) {\n try {\n return JSON.parse(text) as Json;\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction resolveStore(store: CicordClientOptions[\"tokenStore\"], key: string): TokenStore {\n if (store && typeof store === \"object\") return store;\n if (store === \"memory\") return memoryTokenStore();\n const storage = (name: \"localStorage\" | \"sessionStorage\") => {\n try {\n return (globalThis as Record<string, unknown>)[name] as Storage | undefined;\n } catch {\n return undefined;\n }\n };\n return webStorageTokenStore(\n storage(store === \"session\" ? \"sessionStorage\" : \"localStorage\"),\n key,\n );\n}\n\nfunction globalLocation(): LocationLike | undefined {\n return typeof location === \"undefined\" ? undefined : location;\n}\n\nfunction globalHistory(): HistoryLike | undefined {\n return typeof history === \"undefined\" ? undefined : history;\n}\n\nfunction currentPath(): string | undefined {\n const loc = globalLocation();\n if (!loc) return undefined;\n const url = new URL(loc.href);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/** Creates a client. See `CicordClientOptions`. */\nexport function createCicordClient(options?: CicordClientOptions): CicordClient {\n return new CicordClient(options);\n}\n","/**\n * Contract of the `onboarding` plugin's portal routes\n * (examples/basic/plugins/onboarding — `GET /steps`, `POST /complete`).\n */\nimport type { PluginRoutes } from \"./client.ts\";\n\n/** A role a member can pick, resolved by the plugin from the server's roles. */\nexport interface OnboardingOption {\n /** Role key (servers/<server>.yaml). Used in answers. */\n role: string;\n /** Label shown in the portal (config `label`, defaults to the role name). */\n label: string;\n emoji: string;\n description: string;\n /** Discord role name and color (\"\" when the role has none). */\n name: string;\n color: string;\n}\n\nexport interface OnboardingStep {\n id: string;\n title: string;\n description: string;\n /** Several options may be selected. */\n multiple: boolean;\n /** At least one option must be selected. */\n required: boolean;\n options: OnboardingOption[];\n /** Role keys of this step the member currently has. */\n selected: string[];\n}\n\nexport interface OnboardingRole {\n key: string;\n id: string;\n name: string;\n color: string;\n}\n\n/** `GET /steps` */\nexport interface OnboardingSteps {\n title: string;\n intro: string;\n steps: OnboardingStep[];\n /** Role given when the flow is completed, if configured. */\n completedRole: OnboardingRole | null;\n completed: boolean;\n completedAt: string | null;\n}\n\n/** Answers: step id → selected role keys. */\nexport type OnboardingAnswers = Record<string, string[]>;\n\n/** `POST /complete` body. */\nexport interface OnboardingCompleteRequest {\n answers: OnboardingAnswers;\n}\n\n/** `POST /complete` response (200). Errors use the API error shape (`invalid`, 422/400). */\nexport interface OnboardingCompleteResponse {\n completed: true;\n completedAt: string;\n /** Member roles after the update. */\n roles: OnboardingRole[];\n /** Role keys added / removed by this call. */\n added: string[];\n removed: string[];\n /** Success message configured by the server. */\n message: string;\n}\n\n/** Typed wrapper over the onboarding plugin routes. */\nexport function onboardingApi(routes: PluginRoutes) {\n return {\n steps: (init?: { signal?: AbortSignal }) =>\n routes.get<OnboardingSteps>(\"/steps\", undefined, init),\n complete: (answers: OnboardingAnswers, init?: { signal?: AbortSignal }) =>\n routes.post<OnboardingCompleteResponse>(\n \"/complete\",\n { answers } satisfies OnboardingCompleteRequest,\n init,\n ),\n };\n}\n\nexport type OnboardingApi = ReturnType<typeof onboardingApi>;\n","/**\n * Contracts of the showcase plugins' portal routes (examples/showcase): `tickets` and\n * `levels`. They illustrate typing a plugin's routes on top of `client.plugin(...)`; extra\n * fields sent by a plugin are kept as is.\n */\nimport type { CallOptions, PluginRoutes } from \"./client.ts\";\n\nexport type TicketStatus = \"open\" | \"closed\";\n\nexport interface Ticket {\n /** Ticket number, as a string. */\n id: string;\n subject: string;\n status: TicketStatus;\n author: { id: string; displayName: string };\n createdAt: string;\n}\n\n/** tickets `GET /tickets` (moderator), newest first. */\nexport interface TicketList {\n items: Ticket[];\n}\n\nexport interface LeaderboardEntry {\n /** From 1. */\n rank: number;\n userId: string;\n displayName: string;\n avatarUrl: string | null;\n level: number;\n xp: number;\n}\n\n/** levels `GET /leaderboard` (public). */\nexport interface Leaderboard {\n items: LeaderboardEntry[];\n}\n\n/** Typed wrapper over the `tickets` plugin routes. */\nexport function ticketsApi(routes: PluginRoutes) {\n return {\n list: (query: { status?: TicketStatus } = {}, options?: CallOptions) =>\n routes.get<TicketList>(\"/tickets\", query, options),\n };\n}\n\n/** Typed wrapper over the `levels` plugin routes. */\nexport function levelsApi(routes: PluginRoutes) {\n return {\n leaderboard: (query: { limit?: number } = {}, options?: CallOptions) =>\n routes.get<Leaderboard>(\"/leaderboard\", query, options),\n /** levels `GET /me` (member): the viewer's own entry (shape owned by the plugin). */\n me: <T = LeaderboardEntry>(options?: CallOptions) => routes.get<T>(\"/me\", undefined, options),\n };\n}\n"],"mappings":";AAEA,MAAM,iBAA+C;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;;AAGA,SAAgB,cAAc,QAA8B;CAC1D,OAAO,eAAe,YAAY,UAAU,MAAM,aAAa,QAAQ;AACzE;;;;;AAMA,IAAa,iBAAb,MAAa,uBAAuB,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