@powerformer/prism-client 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ import {
2
+ DEFAULT_EDITORIAL_CHANNEL,
3
+ channelNameSchema,
4
+ parseResourceMainV2,
5
+ parseResourceManifestV4,
6
+ resourceDeliveryOrigin,
7
+ resourceEnvironmentSchema,
8
+ resourceLocaleSchema,
9
+ resourcePublicMainPath,
10
+ resourceUuidSchema,
11
+ resourceVersionMainPath,
12
+ resourceVersionManifestPath,
13
+ versionAddressSchema
14
+ } from "./chunk-546JYWIC.js";
15
+
16
+ // app/sdk/errors.ts
17
+ var PrismError = class extends Error {
18
+ code;
19
+ resourceId;
20
+ status;
21
+ constructor(code, message, details = {}) {
22
+ super(message), this.name = "PrismError", this.code = code, this.resourceId = details.resourceId, this.status = details.status;
23
+ }
24
+ };
25
+
26
+ // app/sdk/dev-server.ts
27
+ function startDevServer(store, options) {
28
+ if (store.options.environment !== "dev") throw new PrismError("INVALID_CONFIG", "devServer requires environment dev");
29
+ if (store.watcher) throw new PrismError("INVALID_CONFIG", "This Prism client already has an active devServer");
30
+ let interval = options.pollIntervalMs ?? 2e3;
31
+ if (!Number.isSafeInteger(interval) || interval < 1) throw new PrismError("INVALID_CONFIG", "pollIntervalMs must be a positive integer");
32
+ if (!Array.isArray(options.resources) || options.resources.length === 0) throw new PrismError("INVALID_CONFIG", "devServer resources must not be empty");
33
+ let resources;
34
+ try {
35
+ resources = [...new Set(options.resources.map((id) => resourceUuidSchema.parse(id)))];
36
+ } catch {
37
+ throw new PrismError("INVALID_CONFIG", "Invalid devServer resource ID");
38
+ }
39
+ let closed = !1, failures = 0, timer, running, notifications = /* @__PURE__ */ new Map(), report = (error) => {
40
+ let failure = error instanceof PrismError ? error : new PrismError("NETWORK_ERROR", "Prism development update callback failed");
41
+ try {
42
+ options.onError?.(failure);
43
+ } catch {
44
+ }
45
+ return failure;
46
+ }, cycle = async (initial) => {
47
+ let firstError;
48
+ for (let id of resources) {
49
+ if (closed) break;
50
+ try {
51
+ let previous = store.cache.get(id), entry = initial && previous ? previous : await store.fetch(id);
52
+ if (closed) break;
53
+ previous && previous.main.generation !== entry.main.generation ? notifications.set(id, { resourceId: id, previous: metadata(previous.main), current: metadata(entry.main) }) : !initial && !previous && notifications.set(id, { resourceId: id, previous: null, current: metadata(entry.main) });
54
+ let notification = notifications.get(id);
55
+ notification && (await options.onUpdate?.(notification), notifications.delete(id));
56
+ } catch (error) {
57
+ if (!closed) {
58
+ let failure = report(error);
59
+ firstError ??= failure;
60
+ }
61
+ }
62
+ }
63
+ if (failures = firstError ? Math.min(failures + 1, 5) : 0, initial && firstError) throw firstError;
64
+ }, schedule = () => {
65
+ closed || (timer = setTimeout(() => {
66
+ running = cycle(!1).finally(schedule);
67
+ }, Math.min(interval * 2 ** failures, Math.max(interval, 3e4))));
68
+ };
69
+ running = cycle(!0);
70
+ let ready = running;
71
+ ready.then(schedule, schedule);
72
+ let handle = {
73
+ ready,
74
+ close: async () => {
75
+ closed = !0, clearTimeout(timer);
76
+ for (let id of resources) store.pending.get(id)?.controller.abort();
77
+ await running.catch(() => {
78
+ }), store.watcher === handle && (store.watcher = void 0);
79
+ }
80
+ };
81
+ return store.watcher = handle, handle;
82
+ }
83
+
84
+ // app/sdk/client.ts
85
+ function checked(parse, value, field) {
86
+ try {
87
+ return parse(value);
88
+ } catch {
89
+ throw new PrismError("INVALID_CONFIG", `Invalid ${field}`);
90
+ }
91
+ }
92
+ function positive(value, field) {
93
+ if (!Number.isSafeInteger(value) || value < 1) throw new PrismError("INVALID_CONFIG", `${field} must be a positive integer`);
94
+ return value;
95
+ }
96
+ async function responseJson(response, id, signal) {
97
+ if (!response.ok) throw new PrismError(
98
+ response.status === 404 ? "NOT_PUBLISHED" : "HTTP_ERROR",
99
+ `Prism returned HTTP ${response.status} for ${id}`,
100
+ { resourceId: id, status: response.status }
101
+ );
102
+ try {
103
+ return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(await response.arrayBuffer()));
104
+ } catch (error) {
105
+ throw signal.aborted ? error : new PrismError("INVALID_BUNDLE", `Invalid JSON for ${id}`, { resourceId: id });
106
+ }
107
+ }
108
+ function canonical(value) {
109
+ return Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value && typeof value == "object" ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value);
110
+ }
111
+ function metadata(main) {
112
+ let { mainVersion: _mainVersion, content: _content, defaultLocale: _defaultLocale, ...meta } = main;
113
+ return { ...meta };
114
+ }
115
+ function select(main, requirement) {
116
+ let locale = requirement.locale ?? main.defaultLocale, read = (key) => {
117
+ if (!Object.hasOwn(main.content, key))
118
+ throw new PrismError("LOCALE_NOT_FOUND", `Locale ${key} is not published for ${main.resourceId}`, { resourceId: main.resourceId });
119
+ let copy = structuredClone(main.content[key]);
120
+ if (!requirement.parse) return copy;
121
+ try {
122
+ let result = requirement.parse(copy);
123
+ if (result && (typeof result == "object" || typeof result == "function") && "then" in result && typeof result.then == "function")
124
+ throw Promise.resolve(result).catch(() => {
125
+ }), new Error("Asynchronous parsers are unsupported");
126
+ return result;
127
+ } catch {
128
+ throw new PrismError("CONTENT_VALIDATION_FAILED", `Content validation failed for ${main.resourceId}/${key}`, { resourceId: main.resourceId });
129
+ }
130
+ };
131
+ return requirement.all ? Object.fromEntries(Object.keys(main.content).map((key) => [key, read(key)])) : read(locale);
132
+ }
133
+ var ClientStore = class {
134
+ options;
135
+ cache = /* @__PURE__ */ new Map();
136
+ pending = /* @__PURE__ */ new Map();
137
+ requirements = /* @__PURE__ */ new Map();
138
+ allowedResources;
139
+ watcher;
140
+ constructor(options) {
141
+ if (!options || typeof options != "object") throw new PrismError("INVALID_CONFIG", "Prism options are required");
142
+ this.options = {
143
+ environment: checked(resourceEnvironmentSchema.parse, options.environment, "environment"),
144
+ channel: checked(channelNameSchema.parse, options.channel ?? DEFAULT_EDITORIAL_CHANNEL, "channel"),
145
+ timeoutMs: positive(options.timeoutMs ?? 8e3, "timeoutMs"),
146
+ ...options.version === void 0 ? {} : { version: checked(versionAddressSchema.parse, options.version, "version") }
147
+ };
148
+ }
149
+ parse(value, id) {
150
+ let main;
151
+ try {
152
+ main = parseResourceMainV2(value);
153
+ } catch {
154
+ throw new PrismError("INVALID_BUNDLE", `Invalid main.json for ${id}`, { resourceId: id });
155
+ }
156
+ if (main.resourceId !== id || main.environment !== this.options.environment || main.channel !== this.options.channel)
157
+ throw new PrismError("IDENTITY_MISMATCH", `main.json identity does not match ${id}`, { resourceId: id });
158
+ return main;
159
+ }
160
+ seed(values) {
161
+ let candidates = values.map((value) => {
162
+ let id = checked(resourceUuidSchema.parse, value?.resourceId, "resourceId"), main = this.parse(structuredClone(value), id);
163
+ return [id, { main, etag: null, fingerprint: canonical(main) }];
164
+ });
165
+ for (let [id, entry] of candidates) this.cache.set(id, entry);
166
+ }
167
+ async read(id, requirement) {
168
+ if (this.allowedResources && !this.allowedResources.has(id))
169
+ throw new PrismError("INVALID_CONFIG", `Resource ${id} must be listed in prismContent resources`, { resourceId: id });
170
+ let cached = this.cache.get(id), cachedData = cached ? select(cached.main, requirement) : void 0, requirements = this.requirements.get(id) ?? [], added = !requirements.some((r) => r.locale === requirement.locale && r.all === requirement.all && r.parse === requirement.parse);
171
+ if (added && (requirements.push(requirement), this.requirements.set(id, requirements)), cached) return { entry: cached, data: cachedData };
172
+ try {
173
+ let entry = await this.fetch(id);
174
+ return { entry, data: select(entry.main, requirement) };
175
+ } catch (error) {
176
+ throw added && requirements.splice(requirements.indexOf(requirement), 1), error;
177
+ }
178
+ }
179
+ fetch(id) {
180
+ let existing = this.pending.get(id);
181
+ if (existing) return existing.promise;
182
+ let controller = new AbortController(), promise = this.download(id, controller).finally(() => {
183
+ this.pending.get(id)?.promise === promise && this.pending.delete(id);
184
+ });
185
+ return this.pending.set(id, { promise, controller }), promise;
186
+ }
187
+ async download(id, controller) {
188
+ let previous = this.cache.get(id), timedOut = !1, timer = setTimeout(() => {
189
+ timedOut = !0, controller.abort();
190
+ }, this.options.timeoutMs);
191
+ try {
192
+ let path = this.options.version === void 0 ? resourcePublicMainPath(id, this.options.channel) : resourceVersionMainPath(id, this.options.channel, this.options.version), expectedVersionId = this.options.version === void 0 ? void 0 : previous?.main.versionId;
193
+ if (this.options.version !== void 0 && !expectedVersionId) {
194
+ let response2 = await fetch(new URL(resourceVersionManifestPath(id, this.options.channel, this.options.version), resourceDeliveryOrigin(this.options.environment)), {
195
+ method: "GET",
196
+ cache: "no-store",
197
+ credentials: "omit",
198
+ redirect: "error",
199
+ signal: controller.signal
200
+ }), value2 = await responseJson(response2, id, controller.signal), manifest;
201
+ try {
202
+ manifest = parseResourceManifestV4(value2);
203
+ } catch {
204
+ throw new PrismError("INVALID_BUNDLE", `Invalid version manifest for ${id}`, { resourceId: id });
205
+ }
206
+ if (manifest.resourceId !== id || manifest.environment !== this.options.environment || manifest.channel !== this.options.channel || manifest.mainUrl !== path)
207
+ throw new PrismError("IDENTITY_MISMATCH", `Version manifest identity does not match ${id}`, { resourceId: id });
208
+ expectedVersionId = manifest.versionId;
209
+ }
210
+ let response = await fetch(new URL(path, resourceDeliveryOrigin(this.options.environment)), {
211
+ method: "GET",
212
+ cache: "no-store",
213
+ credentials: "omit",
214
+ redirect: "error",
215
+ headers: previous?.etag ? { "If-None-Match": previous.etag } : {},
216
+ signal: controller.signal
217
+ });
218
+ if (response.status === 304) {
219
+ if (!previous) throw new PrismError("INVALID_BUNDLE", `304 without cached content for ${id}`, { resourceId: id });
220
+ return previous;
221
+ }
222
+ let value = await responseJson(response, id, controller.signal);
223
+ if (controller.signal.aborted) throw new Error("Aborted");
224
+ let main = this.parse(value, id);
225
+ if (expectedVersionId !== void 0 && main.versionId !== expectedVersionId)
226
+ throw new PrismError("IDENTITY_MISMATCH", `main.json Version does not match its manifest for ${id}`, { resourceId: id });
227
+ let fingerprint = canonical(main);
228
+ if (previous) {
229
+ if (main.generation < previous.main.generation) return previous;
230
+ if (main.generation === previous.main.generation && fingerprint !== previous.fingerprint)
231
+ throw new PrismError("PUBLICATION_CONFLICT", `Publication changed without a new generation for ${id}`, { resourceId: id });
232
+ if (main.generation > previous.main.generation && main.publicationId === previous.main.publicationId)
233
+ throw new PrismError("PUBLICATION_CONFLICT", `Publication ID reused for ${id}`, { resourceId: id });
234
+ }
235
+ for (let requirement of this.requirements.get(id) ?? []) select(main, requirement);
236
+ let entry = { main, etag: response.headers.get("etag"), fingerprint };
237
+ return this.cache.set(id, entry), entry;
238
+ } catch (error) {
239
+ if (error instanceof PrismError) throw error;
240
+ let code = timedOut ? "TIMEOUT" : controller.signal.aborted ? "CLOSED" : "NETWORK_ERROR";
241
+ throw new PrismError(code, `${code === "TIMEOUT" ? "Request timed out" : code === "CLOSED" ? "Request cancelled" : "Network request failed"} for ${id}`, { resourceId: id });
242
+ } finally {
243
+ clearTimeout(timer);
244
+ }
245
+ }
246
+ }, stores = /* @__PURE__ */ new WeakMap();
247
+ function storeFor(client) {
248
+ let store = stores.get(client);
249
+ if (!store) throw new PrismError("INVALID_CONFIG", "Unknown Prism client");
250
+ return store;
251
+ }
252
+ var Prism = class _Prism {
253
+ locale;
254
+ constructor(options) {
255
+ stores.set(this, new ClientStore(options)), this.locale = options.locale === void 0 ? void 0 : checked(resourceLocaleSchema.parse, options.locale, "locale");
256
+ }
257
+ localized(locale) {
258
+ let store = storeFor(this), view = new _Prism({ ...store.options, locale });
259
+ return stores.set(view, store), view;
260
+ }
261
+ resource(resourceId, options = {}) {
262
+ let id = checked(resourceUuidSchema.parse, resourceId, "resourceId"), locale = options.locale === void 0 ? this.locale : checked(resourceLocaleSchema.parse, options.locale, "locale");
263
+ if (options.parse !== void 0 && typeof options.parse != "function") throw new PrismError("INVALID_CONFIG", "parse must be a function");
264
+ let store = storeFor(this), parse = options.parse, read = async () => {
265
+ let { entry, data } = await store.read(id, { locale, parse, all: !1 });
266
+ return { data, meta: { ...metadata(entry.main), locale: locale ?? entry.main.defaultLocale } };
267
+ };
268
+ return {
269
+ then: (fulfilled, rejected) => read().then(fulfilled, rejected),
270
+ getAll: async () => {
271
+ let { entry, data } = await store.read(id, { parse, all: !0 });
272
+ return { contents: data, defaultLocale: entry.main.defaultLocale, meta: metadata(entry.main) };
273
+ }
274
+ };
275
+ }
276
+ devServer(options) {
277
+ return startDevServer(storeFor(this), options);
278
+ }
279
+ };
280
+
281
+ export {
282
+ PrismError,
283
+ storeFor,
284
+ Prism
285
+ };
@@ -0,0 +1,31 @@
1
+ import {
2
+ Prism,
3
+ PrismError,
4
+ storeFor
5
+ } from "./chunk-5F3SG6QX.js";
6
+
7
+ // app/sdk/runtime.ts
8
+ var key = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/runtime/v1"), globalRegistry = globalThis, registry = globalRegistry[key] ??= /* @__PURE__ */ new Map();
9
+ function getRuntime(id, options, seeds = [], resources) {
10
+ let existing = registry.get(id);
11
+ if (existing) return existing;
12
+ let client = new Prism(options);
13
+ return storeFor(client).seed(seeds), resources && (storeFor(client).allowedResources = new Set(resources)), registry.set(id, client), client;
14
+ }
15
+ function runtimeSeeds(client, resources) {
16
+ let store = storeFor(client);
17
+ return resources.map((id) => {
18
+ let entry = store.cache.get(id);
19
+ if (!entry) throw new PrismError("NOT_PUBLISHED", `Resource ${id} was not preloaded`, { resourceId: id });
20
+ return structuredClone(entry.main);
21
+ });
22
+ }
23
+ function releaseRuntime(id) {
24
+ registry.delete(id);
25
+ }
26
+
27
+ export {
28
+ getRuntime,
29
+ runtimeSeeds,
30
+ releaseRuntime
31
+ };
@@ -0,0 +1,8 @@
1
+ /** Browser-safe Console permission metadata; separate from immutable delivery manifests. */
2
+ export type ScopeRole = 'owner' | 'member' | null;
3
+ export type ResourceMembership = {
4
+ role: ScopeRole;
5
+ directRole: ScopeRole;
6
+ workspaceRole: ScopeRole;
7
+ inheritedFromWorkspace: boolean;
8
+ };
@@ -0,0 +1,75 @@
1
+ /** Prism delivery protocol. Browser-safe; server hashing lives in publication.ts. */
2
+ import { z } from 'zod/v4';
3
+ import type { ResourceEnvironment, ResourceManifest, ResourceManifestV2, ResourceMain } from './types.js';
4
+ export type { ResourceEnvironment, ResourceManifest, ResourceManifestV2, ResourceMain } from './types.js';
5
+ export declare const RESOURCE_CDN_ORIGIN = "https://r.open-design.ai";
6
+ export declare const MANIFEST_PROTOCOL = "v1";
7
+ export declare const DEFAULT_RESOURCE_CHANNEL = "stable";
8
+ export declare const MANIFEST_CACHE_CONTROL = "no-store";
9
+ export declare const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
10
+ export declare const REVALIDATE_CACHE_CONTROL = "no-cache";
11
+ export declare const resourceIdSchema: z.ZodString;
12
+ export declare const channelNameSchema: z.ZodString;
13
+ export declare const versionIdSchema: z.ZodString;
14
+ /** Optional user label. Length only — not semver grammar. */
15
+ export declare const semanticLabelSchema: z.ZodString;
16
+ /** Creation only. Never use this validator for grandfathered delivery labels. */
17
+ export declare const semanticVersionSchema: z.ZodString;
18
+ export declare const versionAddressSchema: z.ZodString;
19
+ export declare const sha256Schema: z.ZodString;
20
+ export declare function encodeResourcePathSegment(segment: string): string;
21
+ export declare function resourceManifestPath(resourceId: string, channel: string): string;
22
+ export declare function resourceVersionPath(resourceId: string, versionId: string): string;
23
+ export declare function resourceFilePath(sha256: string): string;
24
+ export declare function buildResourceManifest(input: {
25
+ resourceId: string;
26
+ channel: string;
27
+ versionId: string;
28
+ version: string | null;
29
+ contentUrl: string;
30
+ sha256: string;
31
+ }): ResourceManifest;
32
+ /** Accepts unknown extra fields and returns only the known v1 fields. */
33
+ export declare function parseResourceManifest(value: unknown): ResourceManifest;
34
+ /** Parse the exact UTF-8 bytes. Does not reserialize. */
35
+ export declare function assertJsonContentBytes(bytes: Uint8Array): unknown;
36
+ /** V2 keeps the locked v1 API intact and adds independent environments/locales. */
37
+ export declare const RESOURCE_MANIFEST_V2 = "v2";
38
+ export declare const DEFAULT_EDITORIAL_CHANNEL = "default";
39
+ export declare const resourceEnvironmentSchema: z.ZodEnum<{
40
+ dev: "dev";
41
+ prod: "prod";
42
+ }>;
43
+ export declare const resourceLocaleSchema: z.ZodString;
44
+ export declare const publicationIdSchema: z.ZodString;
45
+ export declare function resourceEnvironmentManifestPath(resourceId: string, environment: ResourceEnvironment, channel: string): string;
46
+ export declare function resourceMainPath(resourceId: string, environment: ResourceEnvironment, channel: string): string;
47
+ export declare function resourcePublicationManifestPath(resourceId: string, environment: ResourceEnvironment, publicationId: string): string;
48
+ export declare function resourceLocaleContentPath(resourceId: string, environment: ResourceEnvironment, publicationId: string, locale: string, sha256: string): string;
49
+ export declare function parseResourceManifestV2(value: unknown): ResourceManifestV2;
50
+ export declare function buildResourceManifestV2(input: Omit<ResourceManifestV2, 'manifestVersion'>): ResourceManifestV2;
51
+ export declare function parseResourceMain(value: unknown): ResourceMain;
52
+ /** UUID delivery is a new protocol; the historical functions above remain byte-compatible. */
53
+ export type { ResourceManifestV3, ResourceMainV2 } from './types.js';
54
+ export declare const resourceUuidSchema: z.ZodUUID;
55
+ export declare const slugSchema: z.ZodString;
56
+ export declare function resourceDeliveryOrigin(environment: ResourceEnvironment): string;
57
+ export declare function resourcePublicMainPath(id: string, channel: string): string;
58
+ export declare function resourcePublicManifestPath(id: string, channel: string): string;
59
+ export declare function resourcePublicLocalePath(id: string, channel: string, locale: string): string;
60
+ export declare function resourceVersionMainPath(id: string, channel: string, address: string): string;
61
+ /** Read the address already present in a canonical version main URL; never rederive legacy aliases. */
62
+ export declare function resourceVersionAddressFromMainPath(id: string, channel: string, path: string): string;
63
+ export declare function resourceVersionManifestPath(id: string, channel: string, address: string): string;
64
+ export declare function resourceVersionLocalePath(id: string, channel: string, address: string, locale: string): string;
65
+ export declare function resourcePublicContentPath(id: string, publicationId: string, locale: string, hash: string): string;
66
+ /** Internal key only. Never accept traversal, query strings or arbitrary object prefixes. */
67
+ export declare function resourceStorageKey(environment: ResourceEnvironment, publicPath: string): string;
68
+ export declare function parseResourceManifestV3(value: unknown): import('./types.js').ResourceManifestV3;
69
+ export declare function buildResourceManifestV3(input: Omit<import('./types.js').ResourceManifestV3, 'manifestVersion'>): import('./types.js').ResourceManifestV3;
70
+ export declare function parseResourceMainV2(value: unknown): import('./types.js').ResourceMainV2;
71
+ export declare function parseResourceManifestV4(value: unknown): import('./types.js').ResourceManifestV4;
72
+ export declare function buildResourceManifestV4(input: Omit<import('./types.js').ResourceManifestV4, 'manifestVersion'>): import('./types.js').ResourceManifestV4;
73
+ export declare function parseDeliveryManifest(value: unknown): import('./types.js').DeliveryManifest;
74
+ /** Public paths use the selected environment bucket's custom domain. */
75
+ export declare function resourceDeliveryUrl(path: string, environment: ResourceEnvironment, legacyOrigin?: string): string;
@@ -0,0 +1,54 @@
1
+ /** Portable wire types. Validation is implemented once in resource-manifest.ts. */
2
+ export type ResourceEnvironment = 'dev' | 'prod';
3
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
4
+ [key: string]: JsonValue;
5
+ };
6
+ export type ResourceManifest = {
7
+ manifestVersion: 'v1';
8
+ resourceId: string;
9
+ channel: string;
10
+ versionId: string;
11
+ version: string | null;
12
+ contentUrl: string;
13
+ sha256: string;
14
+ };
15
+ export type PublicationMetadata = {
16
+ resourceId: string;
17
+ environment: ResourceEnvironment;
18
+ channel: string;
19
+ publicationId: string;
20
+ generation: number;
21
+ versionId: string;
22
+ versionRevision: number;
23
+ version: string | null;
24
+ schemaId: string;
25
+ schemaVersion: number;
26
+ defaultLocale: string;
27
+ };
28
+ export type ResourceManifestV2 = PublicationMetadata & {
29
+ manifestVersion: 'v2';
30
+ contentPublicationId: string;
31
+ mainUrl?: string;
32
+ contents: {
33
+ locale: string;
34
+ contentUrl: string;
35
+ sha256: string;
36
+ byteLength: number;
37
+ }[];
38
+ };
39
+ export type ResourceMain = PublicationMetadata & {
40
+ mainVersion: 'v1';
41
+ content: Record<string, JsonValue>;
42
+ };
43
+ export type ResourceManifestV3 = Omit<ResourceManifestV2, 'manifestVersion' | 'mainUrl'> & {
44
+ manifestVersion: 'v3';
45
+ mainUrl: string;
46
+ };
47
+ export type ResourceMainV2 = Omit<ResourceMain, 'mainVersion'> & {
48
+ mainVersion: 'v2';
49
+ };
50
+ /** Both generic and version manifests reference the selected Version's files. */
51
+ export type ResourceManifestV4 = Omit<ResourceManifestV3, 'manifestVersion'> & {
52
+ manifestVersion: 'v4';
53
+ };
54
+ export type DeliveryManifest = ResourceManifestV2 | ResourceManifestV3 | ResourceManifestV4;
@@ -0,0 +1,13 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ export interface PrismContentOptions {
3
+ resources: readonly string[];
4
+ channel?: string;
5
+ version?: string;
6
+ locale?: string;
7
+ timeoutMs?: number;
8
+ devServer?: false | {
9
+ pollIntervalMs?: number;
10
+ update?: 'auto' | 'reload';
11
+ };
12
+ }
13
+ export declare function prismContent(options: PrismContentOptions): AstroIntegration;
@@ -0,0 +1,80 @@
1
+ import {
2
+ getRuntime,
3
+ releaseRuntime,
4
+ runtimeSeeds
5
+ } from "../chunk-PZLXS7XK.js";
6
+ import {
7
+ PrismError
8
+ } from "../chunk-5F3SG6QX.js";
9
+ import "../chunk-546JYWIC.js";
10
+
11
+ // app/sdk/astro.ts
12
+ import { randomUUID } from "node:crypto";
13
+ var virtualId = "virtual:prism", resolvedId = "\0virtual:prism";
14
+ function prismContent(options) {
15
+ if (!options.resources?.length) throw new PrismError("INVALID_CONFIG", "prismContent resources must not be empty");
16
+ if (options.devServer && options.devServer.update && !["auto", "reload"].includes(options.devServer.update))
17
+ throw new PrismError("INVALID_CONFIG", "Unknown Prism update strategy");
18
+ let resources = [...new Set(options.resources)], runtimeId = randomUUID(), client, clientOptions, watcher, seeds = [];
19
+ return {
20
+ name: "@powerformer/prism-client",
21
+ hooks: {
22
+ "astro:config:setup": async ({ command, updateConfig }) => {
23
+ if (!(command === "preview" || command === "sync")) {
24
+ clientOptions = {
25
+ environment: command === "dev" ? "dev" : "prod",
26
+ channel: options.channel,
27
+ version: options.version,
28
+ locale: options.locale,
29
+ timeoutMs: options.timeoutMs
30
+ }, client = getRuntime(runtimeId, clientOptions, [], resources);
31
+ try {
32
+ await Promise.all(resources.map((id) => client.resource(id).getAll()));
33
+ } catch (error) {
34
+ throw releaseRuntime(runtimeId), error;
35
+ }
36
+ seeds = runtimeSeeds(client, resources), updateConfig({ vite: { plugins: [{
37
+ name: "prism-content-runtime",
38
+ resolveId(id) {
39
+ if (id === virtualId) return resolvedId;
40
+ },
41
+ load(id) {
42
+ if (id === resolvedId)
43
+ return `import { getRuntime } from '@powerformer/prism-client/runtime';
44
+ if (!import.meta.env.SSR) throw new Error('virtual:prism is server-only');
45
+ export const prismClient = getRuntime(${JSON.stringify(runtimeId)}, ${JSON.stringify(clientOptions)}, JSON.parse(${JSON.stringify(JSON.stringify(seeds))}), ${JSON.stringify(resources)});`;
46
+ }
47
+ }] } });
48
+ }
49
+ },
50
+ "astro:config:done": ({ injectTypes }) => {
51
+ injectTypes({ filename: "prism.d.ts", content: "declare module 'virtual:prism' { export const prismClient: import('@powerformer/prism-client').Prism; }" });
52
+ },
53
+ "astro:server:setup": async ({ server, logger }) => {
54
+ if (options.devServer === !1) return;
55
+ let settings = options.devServer || {};
56
+ watcher = client.devServer({
57
+ resources,
58
+ pollIntervalMs: settings.pollIntervalMs,
59
+ onError: (error) => logger.error(`${error.code}: ${error.message}`),
60
+ onUpdate: async (update) => {
61
+ seeds = runtimeSeeds(client, resources), server.environments?.ssr?.moduleGraph?.invalidateAll();
62
+ let browser = server.environments?.client, module = browser?.moduleGraph.getModuleById(resolvedId);
63
+ settings.update !== "reload" && module && module.importers.size > 0 ? await browser.reloadModule(module) : (server.moduleGraph.invalidateAll(), server.ws.send({ type: "full-reload" })), logger.info(`Updated ${update.resourceId} to generation ${update.current.generation}`);
64
+ }
65
+ }), server.httpServer?.once("close", () => {
66
+ watcher?.close().finally(() => releaseRuntime(runtimeId));
67
+ }), await watcher.ready;
68
+ },
69
+ "astro:server:done": async () => {
70
+ await watcher?.close(), releaseRuntime(runtimeId);
71
+ },
72
+ "astro:build:done": () => {
73
+ releaseRuntime(runtimeId);
74
+ }
75
+ }
76
+ };
77
+ }
78
+ export {
79
+ prismContent
80
+ };
@@ -0,0 +1,8 @@
1
+ import type { DevServerHandle, DevServerOptions, PrismOptions, ResourceOptions, ResourceQuery } from './types.js';
2
+ export declare class Prism {
3
+ private readonly locale?;
4
+ constructor(options: PrismOptions);
5
+ localized(locale: string): Prism;
6
+ resource<T = unknown>(resourceId: string, options?: ResourceOptions<T>): ResourceQuery<T>;
7
+ devServer(options: DevServerOptions): DevServerHandle;
8
+ }
@@ -0,0 +1,21 @@
1
+ import type { ResourceEnvironment, ResourceMain, ResourceManifest, ResourceManifestV2, ResourceMainV2, ResourceManifestV3, ResourceManifestV4, DeliveryManifest } from '../contracts/types.js';
2
+ export type { JsonValue, ResourceEnvironment, ResourceMain, ResourceManifest, ResourceManifestV2 } from '../contracts/types.js';
3
+ export declare const parseResourceMain: (value: unknown) => ResourceMain;
4
+ export declare const parseResourceManifest: (value: unknown) => ResourceManifest;
5
+ export declare const parseResourceManifestV2: (value: unknown) => ResourceManifestV2;
6
+ export declare const resourceMainPath: (resourceId: string, environment: ResourceEnvironment, channel: string) => string;
7
+ export declare const resourceEnvironmentManifestPath: (resourceId: string, environment: ResourceEnvironment, channel: string) => string;
8
+ export declare const parseResourceMainV2: (value: unknown) => ResourceMainV2;
9
+ export declare const parseResourceManifestV3: (value: unknown) => ResourceManifestV3;
10
+ export declare const resourcePublicMainPath: (id: string, channel: string) => string;
11
+ export declare const resourcePublicManifestPath: (id: string, channel: string) => string;
12
+ export declare const resourcePublicContentPath: (id: string, publicationId: string, locale: string, hash: string) => string;
13
+ export declare const resourceDeliveryOrigin: (environment: ResourceEnvironment) => string;
14
+ export type { ResourceMainV2, ResourceManifestV3 } from '../contracts/types.js';
15
+ export type { ResourceManifestV4, DeliveryManifest } from '../contracts/types.js';
16
+ export declare const parseResourceManifestV4: (value: unknown) => ResourceManifestV4;
17
+ export declare const parseDeliveryManifest: (value: unknown) => DeliveryManifest;
18
+ export declare const resourceVersionMainPath: (id: string, channel: string, address: string) => string;
19
+ export declare const resourceVersionManifestPath: (id: string, channel: string, address: string) => string;
20
+ export declare const resourceVersionLocalePath: (id: string, channel: string, address: string, locale: string) => string;
21
+ export declare const resourcePublicLocalePath: (id: string, channel: string, locale: string) => string;
@@ -0,0 +1,41 @@
1
+ import {
2
+ parseDeliveryManifest,
3
+ parseResourceMain,
4
+ parseResourceMainV2,
5
+ parseResourceManifest,
6
+ parseResourceManifestV2,
7
+ parseResourceManifestV3,
8
+ parseResourceManifestV4,
9
+ resourceDeliveryOrigin,
10
+ resourceEnvironmentManifestPath,
11
+ resourceMainPath,
12
+ resourcePublicContentPath,
13
+ resourcePublicLocalePath,
14
+ resourcePublicMainPath,
15
+ resourcePublicManifestPath,
16
+ resourceVersionLocalePath,
17
+ resourceVersionMainPath,
18
+ resourceVersionManifestPath
19
+ } from "../chunk-546JYWIC.js";
20
+
21
+ // app/sdk/contract.ts
22
+ var parseResourceMain2 = parseResourceMain, parseResourceManifest2 = parseResourceManifest, parseResourceManifestV22 = parseResourceManifestV2, resourceMainPath2 = resourceMainPath, resourceEnvironmentManifestPath2 = resourceEnvironmentManifestPath, parseResourceMainV22 = parseResourceMainV2, parseResourceManifestV32 = parseResourceManifestV3, resourcePublicMainPath2 = resourcePublicMainPath, resourcePublicManifestPath2 = resourcePublicManifestPath, resourcePublicContentPath2 = resourcePublicContentPath, resourceDeliveryOrigin2 = resourceDeliveryOrigin, parseResourceManifestV42 = parseResourceManifestV4, parseDeliveryManifest2 = parseDeliveryManifest, resourceVersionMainPath2 = resourceVersionMainPath, resourceVersionManifestPath2 = resourceVersionManifestPath, resourceVersionLocalePath2 = resourceVersionLocalePath, resourcePublicLocalePath2 = resourcePublicLocalePath;
23
+ export {
24
+ parseDeliveryManifest2 as parseDeliveryManifest,
25
+ parseResourceMain2 as parseResourceMain,
26
+ parseResourceMainV22 as parseResourceMainV2,
27
+ parseResourceManifest2 as parseResourceManifest,
28
+ parseResourceManifestV22 as parseResourceManifestV2,
29
+ parseResourceManifestV32 as parseResourceManifestV3,
30
+ parseResourceManifestV42 as parseResourceManifestV4,
31
+ resourceDeliveryOrigin2 as resourceDeliveryOrigin,
32
+ resourceEnvironmentManifestPath2 as resourceEnvironmentManifestPath,
33
+ resourceMainPath2 as resourceMainPath,
34
+ resourcePublicContentPath2 as resourcePublicContentPath,
35
+ resourcePublicLocalePath2 as resourcePublicLocalePath,
36
+ resourcePublicMainPath2 as resourcePublicMainPath,
37
+ resourcePublicManifestPath2 as resourcePublicManifestPath,
38
+ resourceVersionLocalePath2 as resourceVersionLocalePath,
39
+ resourceVersionMainPath2 as resourceVersionMainPath,
40
+ resourceVersionManifestPath2 as resourceVersionManifestPath
41
+ };
@@ -0,0 +1,10 @@
1
+ export type PrismErrorCode = 'INVALID_CONFIG' | 'NOT_PUBLISHED' | 'LOCALE_NOT_FOUND' | 'INVALID_BUNDLE' | 'IDENTITY_MISMATCH' | 'CONTENT_VALIDATION_FAILED' | 'TIMEOUT' | 'NETWORK_ERROR' | 'HTTP_ERROR' | 'PUBLICATION_CONFLICT' | 'CLOSED';
2
+ export declare class PrismError extends Error {
3
+ readonly code: PrismErrorCode;
4
+ readonly resourceId?: string;
5
+ readonly status?: number;
6
+ constructor(code: PrismErrorCode, message: string, details?: {
7
+ resourceId?: string;
8
+ status?: number;
9
+ });
10
+ }
@@ -0,0 +1,5 @@
1
+ export { Prism } from './client.js';
2
+ export { PrismError } from './errors.js';
3
+ export type { PrismErrorCode } from './errors.js';
4
+ export type { PrismOptions, Environment, ResourceOptions, ResourceQuery, PublicationMeta, ResourceResult, ResourceBundleResult, DevServerOptions, DevServerHandle, DevUpdate, } from './types.js';
5
+ export type { ScopeRole, ResourceMembership } from '../contracts/access.js';
@@ -0,0 +1,9 @@
1
+ import {
2
+ Prism,
3
+ PrismError
4
+ } from "../chunk-5F3SG6QX.js";
5
+ import "../chunk-546JYWIC.js";
6
+ export {
7
+ Prism,
8
+ PrismError
9
+ };
@@ -0,0 +1,5 @@
1
+ import { Prism } from './client.js';
2
+ import type { PrismOptions } from './types.js';
3
+ export declare function getRuntime(id: string, options: PrismOptions, seeds?: readonly unknown[], resources?: readonly string[]): Prism;
4
+ export declare function runtimeSeeds(client: Prism, resources: readonly string[]): unknown[];
5
+ export declare function releaseRuntime(id: string): void;