@edhspace/api 0.0.0-stage → 0.2.0

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 ADDED
@@ -0,0 +1,14 @@
1
+ ISC License
2
+
3
+ Copyright (c) EDHspace contributors
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose
6
+ with or without fee is hereby granted, provided that the above copyright notice
7
+ and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
11
+ FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
12
+ OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
13
+ DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
14
+ ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @edhspace/api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed SDK for EDHspace extensions. React is an optional peer.
4
+
5
+ ```tsx
6
+ import { useActiveDeck, useExtension } from "@edhspace/api/react";
7
+ import { drawProbability } from "@edhspace/api/math";
8
+ ```
9
+
10
+ `useActiveDeck()` and `useSelectedCards()` return `{ data, loading, error, refresh }`.
11
+ `useExtension()` returns the host-scoped client. Mount inside the host's
12
+ `ExtensionProvider`; handle read errors and individual action rejections visibly.
13
+
14
+ The client groups approved external API requests, deck reads/mutation proposals, selection, card inspection and
15
+ lookup, declared workspace panels, notifications, JSON storage and preferences.
16
+ Each method maps to a permission and strict request/result schema. Mutation
17
+ conveniences require a prior deck read; applied receipts require revision/undo
18
+ and advance the client's revision. Method availability depends on the host;
19
+ check the capability reference before using an action.
20
+
21
+ `@edhspace/api/host` is **host-only**: ExtensionSession binds grants to a current
22
+ resource/account generation, validates DTOs and enforces size, replay, rate and
23
+ concurrency limits. Disposal/revocation rejects pending calls. Do not expose the
24
+ workspace runtime, account stores or handler map to extension components.
25
+
26
+ For external APIs, declare `network.request` and HTTPS endpoints, then call
27
+ `api.network.request({ endpoint, path, query })`. Hosts use `createNetworkHandler`
28
+ and `NetworkApprovalQueue` from the host entrypoint to require visible consent.
29
+ GET consent can last for one session; POST always prompts. Calls omit credentials
30
+ and reject redirects. Public services must support browser CORS.
31
+
32
+ Development builds use `@edhspace/api/sideload` to connect an isolated iframe to
33
+ the same capability API over a private message port. The devkit supplies the
34
+ bootstrap; extension components keep using the hooks above. Host integrations
35
+ validate the bundle, own consent and session lifetimes, and never execute
36
+ uploaded code in the application context. See the
37
+ [sideloading contract](../../API.md#development-sideloads).
38
+
39
+ See the [API reference](../../API.md) for manifest fields, interfaces and
40
+ available host capabilities. Unsupported host methods reject explicitly.
41
+
42
+ From this package: `npm run build`, `npm run typecheck`, `npm test`.
43
+ ESM/CommonJS and declarations include shared chunks; retain them when packing.
44
+ `npm pack --dry-run` inspects distribution without publishing.
@@ -0,0 +1,160 @@
1
+ import {
2
+ ExtensionError,
3
+ apiVersion,
4
+ maxRequestBytes,
5
+ maxResponseBytes,
6
+ messageBytes,
7
+ networkRequestSchema,
8
+ parseResult,
9
+ protocol,
10
+ requestSchema,
11
+ responseSchema
12
+ } from "./chunk-LBLXK5J2.js";
13
+
14
+ // src/client.ts
15
+ function createExtensionClient(invoke, sessionId, permissions, timeoutMs = 1e4, networkTimeoutMs = 9e4) {
16
+ const pending = /* @__PURE__ */ new Map();
17
+ let closed = false;
18
+ let revision;
19
+ const call = (method, params) => {
20
+ if (closed)
21
+ return Promise.reject(
22
+ new ExtensionError("Extension access has been revoked.", "revoked")
23
+ );
24
+ if (pending.size >= 4)
25
+ return Promise.reject(new ExtensionError("Too many pending calls.", "rate-limited"));
26
+ const parsed = requestSchema.safeParse({
27
+ protocol,
28
+ apiVersion,
29
+ type: "request",
30
+ sessionId,
31
+ id: crypto.randomUUID(),
32
+ method,
33
+ params
34
+ });
35
+ if (!parsed.success)
36
+ return Promise.reject(
37
+ new ExtensionError("The extension request is invalid.", "invalid")
38
+ );
39
+ const request = parsed.data;
40
+ if (messageBytes(request) > maxRequestBytes)
41
+ return Promise.reject(
42
+ new ExtensionError("The extension request is too large.", "invalid")
43
+ );
44
+ return new Promise((resolve, reject) => {
45
+ const timer = setTimeout(
46
+ () => {
47
+ pending.delete(request.id);
48
+ reject(new ExtensionError("The extension operation timed out.", "timeout"));
49
+ },
50
+ method === "network.request" ? networkTimeoutMs : timeoutMs
51
+ );
52
+ pending.set(request.id, { timer, reject });
53
+ Promise.resolve().then(() => invoke(request)).then(
54
+ (raw) => {
55
+ if (!pending.has(request.id)) return;
56
+ pending.delete(request.id);
57
+ clearTimeout(timer);
58
+ try {
59
+ if (messageBytes(raw) > maxResponseBytes)
60
+ throw new ExtensionError(
61
+ "The extension response is too large.",
62
+ "invalid"
63
+ );
64
+ const response = responseSchema.parse(raw);
65
+ if (response.sessionId !== sessionId || response.id !== request.id)
66
+ throw new ExtensionError(
67
+ "The host response belongs to another request.",
68
+ "invalid"
69
+ );
70
+ if (!response.ok)
71
+ throw new ExtensionError(
72
+ response.error.message,
73
+ response.error.code
74
+ );
75
+ resolve(parseResult(method, response.result));
76
+ } catch (error) {
77
+ reject(
78
+ error instanceof ExtensionError ? error : new ExtensionError(
79
+ "The host returned an invalid response.",
80
+ "invalid"
81
+ )
82
+ );
83
+ }
84
+ },
85
+ (error) => {
86
+ if (!pending.has(request.id)) return;
87
+ pending.delete(request.id);
88
+ clearTimeout(timer);
89
+ if (!(error instanceof ExtensionError))
90
+ console.error("Extension transport failed.", error);
91
+ reject(
92
+ error instanceof ExtensionError ? error : new ExtensionError(
93
+ "The extension operation failed.",
94
+ "unavailable"
95
+ )
96
+ );
97
+ }
98
+ );
99
+ });
100
+ };
101
+ const propose = async (operations) => {
102
+ if (!revision)
103
+ throw new ExtensionError("Read the deck before proposing changes.", "invalid");
104
+ const receipt = await call("deck.propose", { operations, expectedRevision: revision });
105
+ if (receipt.status === "applied") revision = receipt.revision;
106
+ return receipt;
107
+ };
108
+ return {
109
+ permissions: Object.freeze([...permissions]),
110
+ deck: {
111
+ read: async () => {
112
+ const deck = await call("deck.read", {});
113
+ revision = deck.revision;
114
+ return deck;
115
+ },
116
+ propose,
117
+ addCard: (cardId, category, quantity = 1) => propose([{ op: "add", cardId, category, quantity }]),
118
+ removeCard: (cardId, quantity = 1) => propose([{ op: "remove", cardId, quantity }]),
119
+ applyTags: (cardIds, tags) => propose([{ op: "tag", cardIds, tags }])
120
+ },
121
+ selection: { read: () => call("selection.read", {}) },
122
+ network: {
123
+ request: (request) => {
124
+ const parsed = networkRequestSchema.safeParse(request);
125
+ return parsed.success ? call("network.request", parsed.data) : Promise.reject(new ExtensionError("The API request is invalid.", "invalid"));
126
+ }
127
+ },
128
+ cards: {
129
+ inspect: (cardId) => call("cards.inspect", { cardId }),
130
+ search: (query, page = 1) => call("cards.search", { query, page }),
131
+ getByName: (name) => call("cards.get", { name })
132
+ },
133
+ workspace: {
134
+ openPanel: (panelId, location = "workspace") => call("workspace.open", { panelId, location })
135
+ },
136
+ notifications: {
137
+ show: (message, kind = "info") => call("notifications.show", { message, kind })
138
+ },
139
+ storage: {
140
+ get: (key) => call("storage.get", { key }),
141
+ set: (key, value) => call("storage.set", { key, value })
142
+ },
143
+ preferences: {
144
+ get: () => call("preferences.get", {}),
145
+ set: (key, value) => call("preferences.set", { key, value })
146
+ },
147
+ dispose: () => {
148
+ closed = true;
149
+ for (const item of pending.values()) {
150
+ clearTimeout(item.timer);
151
+ item.reject(new ExtensionError("Extension access has been revoked.", "revoked"));
152
+ }
153
+ pending.clear();
154
+ }
155
+ };
156
+ }
157
+
158
+ export {
159
+ createExtensionClient
160
+ };
@@ -0,0 +1,160 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ var _chunkHL56LR6Pcjs = require('./chunk-HL56LR6P.cjs');
13
+
14
+ // src/client.ts
15
+ function createExtensionClient(invoke, sessionId, permissions, timeoutMs = 1e4, networkTimeoutMs = 9e4) {
16
+ const pending = /* @__PURE__ */ new Map();
17
+ let closed = false;
18
+ let revision;
19
+ const call = (method, params) => {
20
+ if (closed)
21
+ return Promise.reject(
22
+ new (0, _chunkHL56LR6Pcjs.ExtensionError)("Extension access has been revoked.", "revoked")
23
+ );
24
+ if (pending.size >= 4)
25
+ return Promise.reject(new (0, _chunkHL56LR6Pcjs.ExtensionError)("Too many pending calls.", "rate-limited"));
26
+ const parsed = _chunkHL56LR6Pcjs.requestSchema.safeParse({
27
+ protocol: _chunkHL56LR6Pcjs.protocol,
28
+ apiVersion: _chunkHL56LR6Pcjs.apiVersion,
29
+ type: "request",
30
+ sessionId,
31
+ id: crypto.randomUUID(),
32
+ method,
33
+ params
34
+ });
35
+ if (!parsed.success)
36
+ return Promise.reject(
37
+ new (0, _chunkHL56LR6Pcjs.ExtensionError)("The extension request is invalid.", "invalid")
38
+ );
39
+ const request = parsed.data;
40
+ if (_chunkHL56LR6Pcjs.messageBytes.call(void 0, request) > _chunkHL56LR6Pcjs.maxRequestBytes)
41
+ return Promise.reject(
42
+ new (0, _chunkHL56LR6Pcjs.ExtensionError)("The extension request is too large.", "invalid")
43
+ );
44
+ return new Promise((resolve, reject) => {
45
+ const timer = setTimeout(
46
+ () => {
47
+ pending.delete(request.id);
48
+ reject(new (0, _chunkHL56LR6Pcjs.ExtensionError)("The extension operation timed out.", "timeout"));
49
+ },
50
+ method === "network.request" ? networkTimeoutMs : timeoutMs
51
+ );
52
+ pending.set(request.id, { timer, reject });
53
+ Promise.resolve().then(() => invoke(request)).then(
54
+ (raw) => {
55
+ if (!pending.has(request.id)) return;
56
+ pending.delete(request.id);
57
+ clearTimeout(timer);
58
+ try {
59
+ if (_chunkHL56LR6Pcjs.messageBytes.call(void 0, raw) > _chunkHL56LR6Pcjs.maxResponseBytes)
60
+ throw new (0, _chunkHL56LR6Pcjs.ExtensionError)(
61
+ "The extension response is too large.",
62
+ "invalid"
63
+ );
64
+ const response = _chunkHL56LR6Pcjs.responseSchema.parse(raw);
65
+ if (response.sessionId !== sessionId || response.id !== request.id)
66
+ throw new (0, _chunkHL56LR6Pcjs.ExtensionError)(
67
+ "The host response belongs to another request.",
68
+ "invalid"
69
+ );
70
+ if (!response.ok)
71
+ throw new (0, _chunkHL56LR6Pcjs.ExtensionError)(
72
+ response.error.message,
73
+ response.error.code
74
+ );
75
+ resolve(_chunkHL56LR6Pcjs.parseResult.call(void 0, method, response.result));
76
+ } catch (error) {
77
+ reject(
78
+ error instanceof _chunkHL56LR6Pcjs.ExtensionError ? error : new (0, _chunkHL56LR6Pcjs.ExtensionError)(
79
+ "The host returned an invalid response.",
80
+ "invalid"
81
+ )
82
+ );
83
+ }
84
+ },
85
+ (error) => {
86
+ if (!pending.has(request.id)) return;
87
+ pending.delete(request.id);
88
+ clearTimeout(timer);
89
+ if (!(error instanceof _chunkHL56LR6Pcjs.ExtensionError))
90
+ console.error("Extension transport failed.", error);
91
+ reject(
92
+ error instanceof _chunkHL56LR6Pcjs.ExtensionError ? error : new (0, _chunkHL56LR6Pcjs.ExtensionError)(
93
+ "The extension operation failed.",
94
+ "unavailable"
95
+ )
96
+ );
97
+ }
98
+ );
99
+ });
100
+ };
101
+ const propose = async (operations) => {
102
+ if (!revision)
103
+ throw new (0, _chunkHL56LR6Pcjs.ExtensionError)("Read the deck before proposing changes.", "invalid");
104
+ const receipt = await call("deck.propose", { operations, expectedRevision: revision });
105
+ if (receipt.status === "applied") revision = receipt.revision;
106
+ return receipt;
107
+ };
108
+ return {
109
+ permissions: Object.freeze([...permissions]),
110
+ deck: {
111
+ read: async () => {
112
+ const deck = await call("deck.read", {});
113
+ revision = deck.revision;
114
+ return deck;
115
+ },
116
+ propose,
117
+ addCard: (cardId, category, quantity = 1) => propose([{ op: "add", cardId, category, quantity }]),
118
+ removeCard: (cardId, quantity = 1) => propose([{ op: "remove", cardId, quantity }]),
119
+ applyTags: (cardIds, tags) => propose([{ op: "tag", cardIds, tags }])
120
+ },
121
+ selection: { read: () => call("selection.read", {}) },
122
+ network: {
123
+ request: (request) => {
124
+ const parsed = _chunkHL56LR6Pcjs.networkRequestSchema.safeParse(request);
125
+ return parsed.success ? call("network.request", parsed.data) : Promise.reject(new (0, _chunkHL56LR6Pcjs.ExtensionError)("The API request is invalid.", "invalid"));
126
+ }
127
+ },
128
+ cards: {
129
+ inspect: (cardId) => call("cards.inspect", { cardId }),
130
+ search: (query, page = 1) => call("cards.search", { query, page }),
131
+ getByName: (name) => call("cards.get", { name })
132
+ },
133
+ workspace: {
134
+ openPanel: (panelId, location = "workspace") => call("workspace.open", { panelId, location })
135
+ },
136
+ notifications: {
137
+ show: (message, kind = "info") => call("notifications.show", { message, kind })
138
+ },
139
+ storage: {
140
+ get: (key) => call("storage.get", { key }),
141
+ set: (key, value) => call("storage.set", { key, value })
142
+ },
143
+ preferences: {
144
+ get: () => call("preferences.get", {}),
145
+ set: (key, value) => call("preferences.set", { key, value })
146
+ },
147
+ dispose: () => {
148
+ closed = true;
149
+ for (const item of pending.values()) {
150
+ clearTimeout(item.timer);
151
+ item.reject(new (0, _chunkHL56LR6Pcjs.ExtensionError)("Extension access has been revoked.", "revoked"));
152
+ }
153
+ pending.clear();
154
+ }
155
+ };
156
+ }
157
+
158
+
159
+
160
+ exports.createExtensionClient = createExtensionClient;
@@ -0,0 +1,311 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/contracts.ts
2
+ var _zod = require('zod');
3
+ var protocol = "edhspace.extension";
4
+ var apiVersion = 1;
5
+ var maxRequestBytes = 8192;
6
+ var maxResponseBytes = 262144;
7
+ var permissionSchema = _zod.z.enum([
8
+ "deck.read",
9
+ "selection.read",
10
+ "deck.propose",
11
+ "cards.inspect",
12
+ "cards.search",
13
+ "workspace.open",
14
+ "notifications.show",
15
+ "storage.read",
16
+ "storage.write",
17
+ "preferences.read",
18
+ "preferences.write",
19
+ "network.request"
20
+ ]);
21
+ var id = _zod.z.string().regex(/^[a-z0-9][a-z0-9.-]{0,99}$/);
22
+ var text = _zod.z.string().trim().min(1).max(300);
23
+ var token = _zod.z.uuid();
24
+ var networkEndpointSchema = _zod.z.strictObject({
25
+ id,
26
+ title: text,
27
+ url: _zod.z.string().max(2e3).refine((value) => {
28
+ try {
29
+ const url = new URL(value);
30
+ const host = url.hostname.replace(/\.$/, "");
31
+ return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && (!url.port || url.port === "443") && host.includes(".") && !host.includes(":") && !/^\d+(?:\.\d+){3}$/.test(host) && !/(?:^|\.)(?:localhost|local|internal|home\.arpa)$/.test(host) && url.pathname.endsWith("/");
32
+ } catch (e) {
33
+ return false;
34
+ }
35
+ }, "Use a public HTTPS base URL ending in /, without credentials or query parameters."),
36
+ methods: _zod.z.array(_zod.z.enum(["GET", "POST"])).min(1).max(2).refine((values) => new Set(values).size === values.length)
37
+ });
38
+ var networkRequestSchema = _zod.z.strictObject({
39
+ endpoint: id,
40
+ path: _zod.z.string().max(500).default("").refine(
41
+ (value) => /^[a-zA-Z0-9._~/-]*$/.test(value) && !value.startsWith("/") && !value.includes("//") && !value.split("/").some((part) => part === "." || part === ".."),
42
+ "Use a relative API path without escaping its base URL."
43
+ ),
44
+ method: _zod.z.enum(["GET", "POST"]).default("GET"),
45
+ query: _zod.z.record(_zod.z.string().min(1).max(100), _zod.z.string().max(2e3)).default({}).refine((values) => Object.keys(values).length <= 20),
46
+ body: _zod.z.json().optional()
47
+ }).refine(
48
+ (value) => value.method !== "GET" || value.body === void 0,
49
+ "GET requests cannot have a body."
50
+ );
51
+ var preferenceSchema = _zod.z.discriminatedUnion("type", [
52
+ _zod.z.strictObject({
53
+ id,
54
+ title: text,
55
+ description: text.optional(),
56
+ type: _zod.z.literal("text"),
57
+ default: _zod.z.string().max(1e3)
58
+ }),
59
+ _zod.z.strictObject({
60
+ id,
61
+ title: text,
62
+ description: text.optional(),
63
+ type: _zod.z.literal("boolean"),
64
+ default: _zod.z.boolean()
65
+ }),
66
+ _zod.z.strictObject({
67
+ id,
68
+ title: text,
69
+ description: text.optional(),
70
+ type: _zod.z.literal("number"),
71
+ default: _zod.z.number().finite()
72
+ }),
73
+ _zod.z.strictObject({
74
+ id,
75
+ title: text,
76
+ description: text.optional(),
77
+ type: _zod.z.literal("select"),
78
+ default: id,
79
+ options: _zod.z.array(_zod.z.strictObject({ value: id, label: text })).min(1).max(30)
80
+ })
81
+ ]).refine(
82
+ (preference) => preference.type !== "select" || preference.options.some((option) => option.value === preference.default),
83
+ "Default must be a declared option."
84
+ );
85
+ var extensionManifestSchema = _zod.z.strictObject({
86
+ id,
87
+ apiVersion: _zod.z.literal(apiVersion),
88
+ version: _zod.z.string().regex(/^\d+\.\d+\.\d+$/),
89
+ title: text,
90
+ description: _zod.z.string().trim().min(1).max(1e3),
91
+ author: text,
92
+ permissions: _zod.z.array(permissionSchema).max(12).refine((items) => new Set(items).size === items.length),
93
+ panels: _zod.z.array(
94
+ _zod.z.strictObject({
95
+ id,
96
+ title: text,
97
+ location: _zod.z.enum(["workspace", "sidebar"]).optional()
98
+ })
99
+ ).min(1).max(6).refine((items) => new Set(items.map((item) => item.id)).size === items.length),
100
+ commands: _zod.z.array(_zod.z.strictObject({ id, title: text })).max(6).default([]),
101
+ preferences: _zod.z.array(preferenceSchema).max(20).default([]).refine((items) => new Set(items.map((item) => item.id)).size === items.length),
102
+ network: _zod.z.array(networkEndpointSchema).max(8).default([]).refine((items) => new Set(items.map((item) => item.id)).size === items.length)
103
+ }).refine(
104
+ (manifest) => manifest.permissions.includes("network.request") === manifest.network.length > 0,
105
+ "Declare network.request and its reviewed API endpoints together."
106
+ );
107
+ var extensionCardSchema = _zod.z.strictObject({
108
+ id: _zod.z.string().min(1).max(200),
109
+ name: text,
110
+ quantity: _zod.z.number().int().min(1).max(1e3),
111
+ manaCost: _zod.z.string().max(200).optional(),
112
+ manaValue: _zod.z.number().min(0).max(1e3).optional(),
113
+ typeLine: text.optional(),
114
+ commander: _zod.z.boolean().optional()
115
+ });
116
+ var extensionDeckSchema = _zod.z.strictObject({
117
+ id: token,
118
+ name: text,
119
+ format: _zod.z.string().min(1).max(50),
120
+ revision: _zod.z.string().min(1).max(200),
121
+ cards: _zod.z.array(extensionCardSchema).max(500)
122
+ });
123
+ var deckOperationSchema = _zod.z.discriminatedUnion("op", [
124
+ _zod.z.strictObject({
125
+ op: _zod.z.literal("add"),
126
+ cardId: text,
127
+ quantity: _zod.z.number().int().min(1).max(75),
128
+ category: id
129
+ }),
130
+ _zod.z.strictObject({
131
+ op: _zod.z.literal("remove"),
132
+ cardId: text,
133
+ quantity: _zod.z.number().int().min(1).max(75)
134
+ }),
135
+ _zod.z.strictObject({
136
+ op: _zod.z.literal("tag"),
137
+ cardIds: _zod.z.array(text).min(1).max(100),
138
+ tags: _zod.z.array(id).max(20)
139
+ })
140
+ ]);
141
+ var proposalReceiptSchema = _zod.z.discriminatedUnion("status", [
142
+ _zod.z.strictObject({
143
+ id: token,
144
+ status: _zod.z.enum(["pending", "dismissed"]),
145
+ revision: text.optional(),
146
+ undoId: token.optional()
147
+ }),
148
+ _zod.z.strictObject({ id: token, status: _zod.z.literal("applied"), revision: text, undoId: token })
149
+ ]);
150
+ var envelope = {
151
+ protocol: _zod.z.literal(protocol),
152
+ apiVersion: _zod.z.literal(apiVersion),
153
+ sessionId: token
154
+ };
155
+ var base = { ...envelope, type: _zod.z.literal("request"), id: token };
156
+ var requestSchema = _zod.z.discriminatedUnion("method", [
157
+ _zod.z.strictObject({ ...base, method: _zod.z.literal("network.request"), params: networkRequestSchema }),
158
+ _zod.z.strictObject({ ...base, method: _zod.z.literal("deck.read"), params: _zod.z.strictObject({}) }),
159
+ _zod.z.strictObject({ ...base, method: _zod.z.literal("selection.read"), params: _zod.z.strictObject({}) }),
160
+ _zod.z.strictObject({
161
+ ...base,
162
+ method: _zod.z.literal("deck.propose"),
163
+ params: _zod.z.strictObject({
164
+ expectedRevision: text,
165
+ operations: _zod.z.array(deckOperationSchema).min(1).max(75)
166
+ })
167
+ }),
168
+ _zod.z.strictObject({
169
+ ...base,
170
+ method: _zod.z.literal("cards.inspect"),
171
+ params: _zod.z.strictObject({ cardId: text })
172
+ }),
173
+ _zod.z.strictObject({
174
+ ...base,
175
+ method: _zod.z.literal("cards.search"),
176
+ params: _zod.z.strictObject({ query: text, page: _zod.z.number().int().min(1).max(20) })
177
+ }),
178
+ _zod.z.strictObject({
179
+ ...base,
180
+ method: _zod.z.literal("cards.get"),
181
+ params: _zod.z.strictObject({ name: text })
182
+ }),
183
+ _zod.z.strictObject({
184
+ ...base,
185
+ method: _zod.z.literal("workspace.open"),
186
+ params: _zod.z.strictObject({ panelId: id, location: _zod.z.enum(["workspace", "sidebar"]) })
187
+ }),
188
+ _zod.z.strictObject({
189
+ ...base,
190
+ method: _zod.z.literal("notifications.show"),
191
+ params: _zod.z.strictObject({ message: text, kind: _zod.z.enum(["info", "success", "error"]) })
192
+ }),
193
+ _zod.z.strictObject({
194
+ ...base,
195
+ method: _zod.z.literal("storage.get"),
196
+ params: _zod.z.strictObject({ key: id })
197
+ }),
198
+ _zod.z.strictObject({
199
+ ...base,
200
+ method: _zod.z.literal("storage.set"),
201
+ params: _zod.z.strictObject({ key: id, value: _zod.z.json() })
202
+ }),
203
+ _zod.z.strictObject({ ...base, method: _zod.z.literal("preferences.get"), params: _zod.z.strictObject({}) }),
204
+ _zod.z.strictObject({
205
+ ...base,
206
+ method: _zod.z.literal("preferences.set"),
207
+ params: _zod.z.strictObject({ key: id, value: _zod.z.json() })
208
+ })
209
+ ]);
210
+ var resultSchemas = {
211
+ "network.request": _zod.z.strictObject({
212
+ status: _zod.z.number().int().min(200).max(299),
213
+ data: _zod.z.json()
214
+ }),
215
+ "deck.read": extensionDeckSchema,
216
+ "selection.read": _zod.z.array(extensionCardSchema).max(100),
217
+ "deck.propose": proposalReceiptSchema,
218
+ "cards.inspect": _zod.z.strictObject({ opened: _zod.z.literal(true) }),
219
+ "cards.search": _zod.z.strictObject({
220
+ cards: _zod.z.array(extensionCardSchema).max(100),
221
+ nextPage: _zod.z.number().int().min(1).max(20).optional()
222
+ }),
223
+ "cards.get": extensionCardSchema.nullable(),
224
+ "workspace.open": _zod.z.strictObject({ panelId: id }),
225
+ "notifications.show": _zod.z.strictObject({ shown: _zod.z.literal(true) }),
226
+ "storage.get": _zod.z.json(),
227
+ "storage.set": _zod.z.strictObject({ saved: _zod.z.literal(true) }),
228
+ "preferences.get": _zod.z.record(_zod.z.string(), _zod.z.json()),
229
+ "preferences.set": _zod.z.strictObject({ saved: _zod.z.literal(true) })
230
+ };
231
+ var methodPermissions = {
232
+ "network.request": "network.request",
233
+ "deck.read": "deck.read",
234
+ "selection.read": "selection.read",
235
+ "deck.propose": "deck.propose",
236
+ "cards.inspect": "cards.inspect",
237
+ "cards.search": "cards.search",
238
+ "cards.get": "cards.search",
239
+ "workspace.open": "workspace.open",
240
+ "notifications.show": "notifications.show",
241
+ "storage.get": "storage.read",
242
+ "storage.set": "storage.write",
243
+ "preferences.get": "preferences.read",
244
+ "preferences.set": "preferences.write"
245
+ };
246
+ var errorCodeSchema = _zod.z.enum([
247
+ "invalid",
248
+ "denied",
249
+ "revoked",
250
+ "unavailable",
251
+ "rate-limited",
252
+ "replayed",
253
+ "timeout",
254
+ "disconnected"
255
+ ]);
256
+ var ExtensionError = class extends Error {
257
+ constructor(message, code) {
258
+ super(message);
259
+ this.code = code;
260
+ this.name = "ExtensionError";
261
+ }
262
+ };
263
+ var responseSchema = _zod.z.discriminatedUnion("ok", [
264
+ _zod.z.strictObject({
265
+ ...envelope,
266
+ type: _zod.z.literal("response"),
267
+ id: token,
268
+ ok: _zod.z.literal(true),
269
+ result: _zod.z.unknown()
270
+ }),
271
+ _zod.z.strictObject({
272
+ ...envelope,
273
+ type: _zod.z.literal("response"),
274
+ id: token,
275
+ ok: _zod.z.literal(false),
276
+ error: _zod.z.strictObject({ code: errorCodeSchema, message: _zod.z.string().max(300) })
277
+ })
278
+ ]);
279
+ function messageBytes(value) {
280
+ try {
281
+ const encoded = JSON.stringify(value);
282
+ if (!encoded) throw new Error("Missing message.");
283
+ return new TextEncoder().encode(encoded).byteLength;
284
+ } catch (e2) {
285
+ throw new ExtensionError("The extension message is not serializable.", "invalid");
286
+ }
287
+ }
288
+ function parseResult(method, value) {
289
+ const result = resultSchemas[method].safeParse(value);
290
+ if (!result.success)
291
+ throw new ExtensionError("The host returned an invalid result.", "invalid");
292
+ return result.data;
293
+ }
294
+
295
+
296
+
297
+
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+ exports.protocol = protocol; exports.apiVersion = apiVersion; exports.maxRequestBytes = maxRequestBytes; exports.maxResponseBytes = maxResponseBytes; exports.permissionSchema = permissionSchema; exports.networkEndpointSchema = networkEndpointSchema; exports.networkRequestSchema = networkRequestSchema; exports.preferenceSchema = preferenceSchema; exports.extensionManifestSchema = extensionManifestSchema; exports.requestSchema = requestSchema; exports.methodPermissions = methodPermissions; exports.ExtensionError = ExtensionError; exports.responseSchema = responseSchema; exports.messageBytes = messageBytes; exports.parseResult = parseResult;