@scalar/workspace-store 0.9.0 → 0.10.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.
- package/CHANGELOG.md +27 -0
- package/dist/client.d.ts +2 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +24 -12
- package/dist/client.js.map +2 -2
- package/dist/helpers/proxy.d.ts +1 -1
- package/dist/helpers/proxy.d.ts.map +1 -1
- package/dist/helpers/proxy.js +2 -2
- package/dist/helpers/proxy.js.map +2 -2
- package/dist/mutators/helpers.d.ts +1699 -1447
- package/dist/mutators/helpers.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-paths.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-paths.js +3 -2
- package/dist/navigation/helpers/traverse-paths.js.map +2 -2
- package/dist/navigation/helpers/traverse-schemas.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-schemas.js +6 -5
- package/dist/navigation/helpers/traverse-schemas.js.map +2 -2
- package/dist/navigation/helpers/traverse-tags.js +2 -2
- package/dist/navigation/helpers/traverse-tags.js.map +2 -2
- package/dist/navigation/types.d.ts +2 -0
- package/dist/navigation/types.d.ts.map +1 -1
- package/dist/schemas/inmemory-workspace.d.ts +1 -1
- package/dist/schemas/v3.1/strict/callback.d.ts +8 -1
- package/dist/schemas/v3.1/strict/callback.d.ts.map +1 -1
- package/dist/schemas/v3.1/strict/callback.js +2 -1
- package/dist/schemas/v3.1/strict/callback.js.map +2 -2
- package/dist/schemas/v3.1/strict/path-operations.d.ts +90 -13
- package/dist/schemas/v3.1/strict/path-operations.d.ts.map +1 -1
- package/dist/schemas/v3.1/strict/paths.d.ts +72 -9
- package/dist/schemas/v3.1/strict/paths.d.ts.map +1 -1
- package/dist/schemas/workspace-specification/index.d.ts +1 -1
- package/dist/schemas/workspace.d.ts +2 -2
- package/dist/schemas/workspace.d.ts.map +1 -1
- package/dist/schemas/workspace.js +2 -1
- package/dist/schemas/workspace.js.map +2 -2
- package/dist/server.d.ts +137 -119
- package/dist/server.d.ts.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# @scalar/workspace-store
|
|
2
2
|
|
|
3
|
+
## 0.10.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 3f2ea8a: fix: shows different console errors whether the request wasn't successful or the data isn't a valid object
|
|
8
|
+
- 828c894: fix: update workspace traversal with fixes from sidebar
|
|
9
|
+
- b5bcce7: feat: implement new request example openapi block in references
|
|
10
|
+
- Updated dependencies [591562f]
|
|
11
|
+
- Updated dependencies [85ee2ce]
|
|
12
|
+
- Updated dependencies [85ee2ce]
|
|
13
|
+
- @scalar/openapi-types@0.3.6
|
|
14
|
+
- @scalar/types@0.2.9
|
|
15
|
+
- @scalar/code-highlight@0.1.8
|
|
16
|
+
- @scalar/openapi-parser@0.18.1
|
|
17
|
+
|
|
18
|
+
## 0.10.0
|
|
19
|
+
|
|
20
|
+
### Minor Changes
|
|
21
|
+
|
|
22
|
+
- 8b9c48e: fix(workspace-store): support local ref resolution on arrays
|
|
23
|
+
|
|
24
|
+
### Patch Changes
|
|
25
|
+
|
|
26
|
+
- a85480e: feat: lay the groundwork for the block implementation PR
|
|
27
|
+
- Updated dependencies [6ab3a21]
|
|
28
|
+
- @scalar/code-highlight@0.1.7
|
|
29
|
+
|
|
3
30
|
## 0.9.0
|
|
4
31
|
|
|
5
32
|
### Minor Changes
|
package/dist/client.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type createNavigationOptions } from './navigation/index.js';
|
|
2
|
-
import type {
|
|
3
|
-
import type { WorkspaceMeta, WorkspaceDocumentMeta, Workspace } from './schemas/workspace.js';
|
|
2
|
+
import type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from './schemas/workspace.js';
|
|
4
3
|
import type { Config } from './schemas/workspace-specification/config.js';
|
|
4
|
+
import type { DeepTransform } from './types.js';
|
|
5
5
|
/**
|
|
6
6
|
* Input type for workspace document metadata and configuration.
|
|
7
7
|
* This type defines the required and optional fields for initializing a document in the workspace.
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAUA,OAAO,EAAoB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAM7E,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAC1F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0CAA0C,CAAA;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE5C;;;;;GAKG;AACH,KAAK,0BAA0B,GAAG;IAChC,wEAAwE;IACxE,IAAI,CAAC,EAAE,qBAAqB,CAAA;IAC5B,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAA;IACZ,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAA;CACnD,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,MAAM,GAAG;IACnB,6CAA6C;IAC7C,GAAG,EAAE,MAAM,CAAA;IACX,wIAAwI;IACxI,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CAC5F,GAAG,0BAA0B,CAAA;AAE9B,iGAAiG;AACjG,MAAM,MAAM,SAAS,GAAG;IACtB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAClC,GAAG,0BAA0B,CAAA;AAE9B;;;;GAIG;AACH,MA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8F;IAC9F,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,EAAE,GAAG,SAAS,CAAA;IACzD,2DAA2D;IAC3D,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IACjD,qCAAqC;IACrC,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1C,mGAAmG;IACnG,eAAe,IAAI,MAAM,CAAA;IACzB,yDAAyD;IACzD,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CACnC,CAAA;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,oBAAoB,oBAAqB,cAAc,KAAG,cAobtE,CAAA;AAGD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA"}
|
package/dist/client.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import YAML from "yaml";
|
|
2
|
-
import { reactive, toRaw } from "vue";
|
|
3
1
|
import { bundle, upgrade } from "@scalar/openapi-parser";
|
|
4
2
|
import { fetchUrls } from "@scalar/openapi-parser/plugins-browser";
|
|
5
|
-
import {
|
|
6
|
-
import
|
|
7
|
-
import { deepClone, isObject, safeAssign } from "./helpers/general.js";
|
|
8
|
-
import { mergeObjects } from "./helpers/merge-object.js";
|
|
3
|
+
import { reactive, toRaw } from "vue";
|
|
4
|
+
import YAML from "yaml";
|
|
9
5
|
import { applySelectiveUpdates } from "./helpers/apply-selective-updates.js";
|
|
6
|
+
import { deepClone, isObject, safeAssign } from "./helpers/general.js";
|
|
10
7
|
import { getValueByPath } from "./helpers/json-path-utils.js";
|
|
8
|
+
import { mergeObjects } from "./helpers/merge-object.js";
|
|
9
|
+
import { createMagicProxy, getRaw } from "./helpers/proxy.js";
|
|
10
|
+
import { createNavigation } from "./navigation/index.js";
|
|
11
11
|
import { extensions } from "./schemas/extensions.js";
|
|
12
|
+
import { InMemoryWorkspaceSchema } from "./schemas/inmemory-workspace.js";
|
|
13
|
+
import { defaultReferenceConfig } from "./schemas/reference-config/index.js";
|
|
12
14
|
import { coerceValue } from "./schemas/typebox-coerce.js";
|
|
13
15
|
import { OpenAPIDocumentSchema } from "./schemas/v3.1/strict/openapi-document.js";
|
|
14
|
-
import { defaultReferenceConfig } from "./schemas/reference-config/index.js";
|
|
15
|
-
import { InMemoryWorkspaceSchema } from "./schemas/inmemory-workspace.js";
|
|
16
16
|
const defaultConfig = {
|
|
17
17
|
"x-scalar-reference-config": defaultReferenceConfig
|
|
18
18
|
};
|
|
@@ -157,15 +157,27 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
157
157
|
addDocument: async (input) => {
|
|
158
158
|
const { name, meta, config } = input;
|
|
159
159
|
const resolve = await loadDocument(input);
|
|
160
|
-
if (!resolve.ok
|
|
161
|
-
console.error(`
|
|
160
|
+
if (!resolve.ok) {
|
|
161
|
+
console.error(`Failed to fetch document '${name}': request was not successful`);
|
|
162
162
|
workspace.documents[name] = {
|
|
163
163
|
...meta,
|
|
164
|
+
openapi: "3.1.0",
|
|
164
165
|
info: {
|
|
165
166
|
title: `Document '${name}' could not be loaded`,
|
|
166
167
|
version: "unknown"
|
|
167
|
-
}
|
|
168
|
-
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (!isObject(resolve.data)) {
|
|
173
|
+
console.error(`Failed to load document '${name}': response data is not a valid object`);
|
|
174
|
+
workspace.documents[name] = {
|
|
175
|
+
...meta,
|
|
176
|
+
openapi: "3.1.0",
|
|
177
|
+
info: {
|
|
178
|
+
title: `Document '${name}' could not be loaded`,
|
|
179
|
+
version: "unknown"
|
|
180
|
+
}
|
|
169
181
|
};
|
|
170
182
|
return;
|
|
171
183
|
}
|
package/dist/client.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["import YAML from 'yaml'\nimport { reactive, toRaw } from 'vue'\nimport { bundle, upgrade } from '@scalar/openapi-parser'\nimport { fetchUrls } from '@scalar/openapi-parser/plugins-browser'\n\nimport { createNavigation, type createNavigationOptions } from '@/navigation'\nimport type { DeepTransform } from '@/types'\nimport { createMagicProxy, getRaw } from '@/helpers/proxy'\nimport { deepClone, isObject, safeAssign } from '@/helpers/general'\nimport { mergeObjects } from '@/helpers/merge-object'\nimport { applySelectiveUpdates } from '@/helpers/apply-selective-updates'\nimport { getValueByPath } from '@/helpers/json-path-utils'\nimport type { WorkspaceMeta, WorkspaceDocumentMeta, Workspace } from '@/schemas/workspace'\nimport { extensions } from '@/schemas/extensions'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema } from '@/schemas/v3.1/strict/openapi-document'\nimport { defaultReferenceConfig } from '@/schemas/reference-config'\nimport type { Config } from '@/schemas/workspace-specification/config'\nimport { InMemoryWorkspaceSchema, type InMemoryWorkspace } from '@/schemas/inmemory-workspace'\n\n/**\n * Input type for workspace document metadata and configuration.\n * This type defines the required and optional fields for initializing a document in the workspace.\n *\n * TODO: merge navigation options with the document config\n */\ntype WorkspaceDocumentMetaInput = {\n /** Optional metadata about the document like title, description, etc */\n meta?: WorkspaceDocumentMeta\n /** Required unique identifier for the document */\n name: string\n /** Optional configuration for generating navigation structure */\n config?: Config & Partial<createNavigationOptions>\n}\n\n/**\n * Represents a document that is loaded from a URL.\n * This type extends WorkspaceDocumentMetaInput to include URL-specific properties.\n */\nexport type UrlDoc = {\n /** URL to fetch the OpenAPI document from */\n url: string\n /** Optional custom fetch implementation to use when retrieving the document. By default the global fetch implementation will be used */\n fetch?: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n} & WorkspaceDocumentMetaInput\n\n/** Represents a document that is provided directly as an object rather than loaded from a URL */\nexport type ObjectDoc = {\n /** The OpenAPI document object containing the API specification */\n document: Record<string, unknown>\n} & WorkspaceDocumentMetaInput\n\n/**\n * Union type representing the possible input formats for a workspace document:\n * - UrlDoc: Document loaded from a URL with optional fetch configuration\n * - ObjectDoc: Direct document object with metadata\n */\nexport type WorkspaceDocumentInput = UrlDoc | ObjectDoc\n\nconst defaultConfig: DeepTransform<Config, 'NonNullable'> = {\n 'x-scalar-reference-config': defaultReferenceConfig,\n}\n\n/**\n * Resolves a workspace document from various input sources (URL, local file, or direct document object).\n *\n * @param workspaceDocument - The document input to resolve, which can be:\n * - A URL to fetch the document from\n * - A direct document object\n * @returns A promise that resolves to an object containing:\n * - ok: boolean indicating if the resolution was successful\n * - data: The resolved document data\n *\n * @example\n * // Resolve from URL\n * const urlDoc = await loadDocument({ name: 'api', url: 'https://api.example.com/openapi.json' })\n *\n * // Resolve direct document\n * const directDoc = await loadDocument({\n * name: 'inline',\n * document: { openapi: '3.0.0', paths: {} }\n * })\n */\nasync function loadDocument(workspaceDocument: WorkspaceDocumentInput) {\n if ('url' in workspaceDocument) {\n return fetchUrls({ fetch: workspaceDocument.fetch }).exec(workspaceDocument.url)\n }\n\n return {\n ok: true as const,\n data: workspaceDocument.document,\n }\n}\n\n/**\n * Configuration object for initializing a workspace store.\n * Defines the initial state and documents for the workspace.\n */\ntype WorkspaceProps = {\n /** Optional metadata for the workspace including theme, active document, etc */\n meta?: WorkspaceMeta\n /** In-mem open api documents. Async source documents (like URLs) can be loaded after initialization */\n documents?: ObjectDoc[]\n /** Workspace configuration */\n config?: Config\n}\n\n/**\n * Type definition for the workspace store return object.\n * This explicit type is needed to avoid TypeScript inference limits.\n *\n * @see https://github.com/microsoft/TypeScript/issues/43817#issuecomment-827746462\n */\nexport type WorkspaceStore = {\n /** Returns the reactive workspace object with an additional activeDocument getter */\n readonly workspace: Workspace\n /** Updates a specific metadata field in the workspace */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]): void\n /** Updates a specific metadata field in a document */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ): void\n /** Resolves a reference in the active document by following the provided path and resolving any external $ref references */\n resolve(path: string[]): Promise<unknown>\n /** Adds a new document to the workspace */\n addDocument(input: WorkspaceDocumentInput): Promise<void>\n /** Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously */\n addDocumentSync(input: ObjectDoc): void\n /** Returns the merged configuration for the active document */\n readonly config: typeof defaultConfig\n /** Downloads the specified document in the requested format */\n exportDocument(documentName: string, format: 'json' | 'yaml'): string | undefined\n /** Persists the current state of the specified document back to the original documents map */\n saveDocument(documentName: string): unknown[] | undefined\n /** Reverts the specified document to its original state */\n revertDocumentChanges(documentName: string): void\n /** Commits the specified document */\n commitDocument(documentName: string): void\n /** Serializes the current workspace state to a JSON string for backup, persistence, or sharing. */\n exportWorkspace(): string\n /** Imports a workspace from a serialized JSON string. */\n loadWorkspace(input: string): void\n}\n\n/**\n * Creates a reactive workspace store that manages documents and their metadata.\n * The store provides functionality for accessing, updating, and resolving document references.\n *\n * @param workspaceProps - Configuration object for the workspace\n * @param workspaceProps.meta - Optional metadata for the workspace\n * @param workspaceProps.documents - Optional record of documents to initialize the workspace with\n * Documents that require asynchronous loading must be added using `addDocument` after the store is created\n * this allows atomic awaiting and does not block page load for the store initialization\n * @returns An object containing methods and getters for managing the workspace\n */\nexport const createWorkspaceStore = (workspaceProps?: WorkspaceProps): WorkspaceStore => {\n /**\n * Holds the original, unmodified documents as they were initially loaded into the workspace.\n * These documents are stored in their raw form\u2014prior to any reactive wrapping, dereferencing, or bundling.\n * This map preserves the pristine structure of each document, using deep clones to ensure that\n * subsequent mutations in the workspace do not affect the originals.\n * The originals are retained so that we can restore, compare, or sync with the remote registry as needed.\n */\n const originalDocuments = {} as Workspace['documents']\n\n /**\n * Stores the intermediate state of documents after local edits but before syncing with the remote registry.\n *\n * This map acts as a local \"saved\" version of the document, reflecting the user's changes after they hit \"save\".\n * The `originalDocuments` map, by contrast, always mirrors the document as it exists in the remote registry.\n *\n * Use this map to stage local changes that are ready to be propagated back to the remote registry.\n * This separation allows us to distinguish between:\n * - The last known remote version (`originalDocuments`)\n * - The latest locally saved version (`intermediateDocuments`)\n * - The current in-memory (possibly unsaved) workspace document (`workspace.documents`)\n */\n const intermediateDocuments = {} as Workspace['documents']\n /**\n * A map of document configurations keyed by document name.\n * This stores the configuration options for each document in the workspace,\n * allowing for document-specific settings like navigation options, appearance,\n * and other reference configuration.\n */\n const documentConfigs: Record<string, Config> = {}\n\n // Create a reactive workspace object with proxied documents\n // Each document is wrapped in a proxy to enable reactive updates and reference resolution\n const workspace = reactive<Workspace>({\n ...workspaceProps?.meta,\n documents: {},\n /**\n * Returns the currently active document from the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The active document or undefined if no document is found\n */\n get activeDocument(): NonNullable<Workspace['activeDocument']> | undefined {\n const activeDocumentKey =\n workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n return workspace.documents[activeDocumentKey]\n },\n })\n\n /**\n * Returns the name of the currently active document in the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The name of the active document or an empty string if no document is found\n */\n function getActiveDocumentName() {\n return workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n }\n\n // Add a document to the store synchronously from an in-memory OpenAPI document\n function addDocumentSync(input: ObjectDoc) {\n const { name, meta } = input\n\n const document = coerceValue(OpenAPIDocumentSchema, upgrade(input.document).specification)\n\n // Store the original document in the originalDocuments map\n // This is used to track the original state of the document as it was loaded into the workspace\n originalDocuments[name] = deepClone({ ...document, ...meta })\n // Store the intermediate document state for local edits\n // This is used to track the last saved state of the document\n // It allows us to differentiate between the original document and the latest saved version\n // This is important for local edits that are not yet synced with the remote registry\n // The intermediate document is used to store the latest saved state of the document\n // This allows us to track changes and revert to the last saved state if needed\n intermediateDocuments[name] = deepClone({ ...document, ...meta })\n // Add the document config to the documentConfigs map\n documentConfigs[name] = input.config ?? {}\n\n // Skip navigation generation if the document already has a server-side generated navigation structure\n if (document[extensions.document.navigation] === undefined) {\n document[extensions.document.navigation] = createNavigation(document, input.config ?? {}).entries\n }\n\n workspace.documents[name] = createMagicProxy({ ...document, ...meta })\n }\n\n // Add any initial documents to the store\n workspaceProps?.documents?.forEach(addDocumentSync)\n\n // Cache to track visited nodes during reference resolution to prevent bundling the same subtree multiple times\n // This is needed because we are doing partial bundle operations\n const visitedNodesCache = new Set()\n\n return {\n /**\n * Returns the reactive workspace object with an additional activeDocument getter\n */\n get workspace() {\n return workspace\n },\n /**\n * Updates a specific metadata field in the workspace\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @example\n * // Update the workspace title\n * update('x-scalar-active-document', 'document-name')\n */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]) {\n // @ts-ignore\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n throw new Error('Invalid key: cannot modify prototype')\n }\n Object.assign(workspace, { [key]: value })\n },\n /**\n * Updates a specific metadata field in a document\n * @param name - The name of the document to update ('active' or a specific document name)\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @throws Error if the specified document doesn't exist\n * @example\n * // Update the auth of the active document\n * updateDocument('active', 'x-scalar-active-auth', 'Bearer')\n * // Update the auth of a specific document\n * updateDocument('document-name', 'x-scalar-active-auth', 'Bearer')\n */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ) {\n const currentDocument = workspace.documents[name === 'active' ? getActiveDocumentName() : name]\n\n if (!currentDocument) {\n throw 'Please select a valid document'\n }\n\n Object.assign(currentDocument, { [key]: value })\n },\n /**\n * Resolves a reference in the active document by following the provided path and resolving any external $ref references.\n * This method traverses the document structure following the given path and resolves any $ref references it encounters.\n * During resolution, it sets a loading status and updates the reference with the resolved content.\n *\n * @param path - Array of strings representing the path to the reference (e.g. ['paths', '/users', 'get', 'responses', '200'])\n * @throws Error if the path is invalid or empty\n * @example\n * // Resolve a reference in the active document\n * resolve(['paths', '/users', 'get', 'responses', '200'])\n */\n resolve: async (path: string[]) => {\n const activeDocument = workspace.activeDocument\n\n const target = getValueByPath(activeDocument, path)\n\n if (!isObject(target)) {\n console.error(\n `Invalid path provided for resolution. Path: [${path.join(', ')}]. Found value of type: ${typeof target}. Expected an object.`,\n )\n return\n }\n\n // Bundle the target document with the active document as root, resolving any external references\n // and tracking resolution status through hooks\n return bundle(target, {\n root: activeDocument,\n treeShake: false,\n plugins: [fetchUrls()],\n urlMap: false,\n hooks: {\n onResolveStart: (node) => {\n node['$status'] = 'loading'\n },\n onResolveError: (node) => {\n node['$status'] = 'error'\n },\n },\n visitedNodes: visitedNodesCache,\n })\n },\n /**\n * Adds a new document to the workspace\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocument: async (input: WorkspaceDocumentInput) => {\n const { name, meta, config } = input\n\n const resolve = await loadDocument(input)\n\n if (!resolve.ok || !isObject(resolve.data)) {\n console.error(`Can not load the document '${name}'`)\n workspace.documents[name] = {\n ...meta,\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n openapi: '3.1.0',\n }\n return\n }\n\n addDocumentSync({ document: resolve.data, name, meta, config })\n },\n /**\n * Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocumentSync,\n /**\n * Returns the merged configuration for the active document.\n *\n * This getter merges configurations in the following order of precedence:\n * 1. Document-specific configuration (highest priority)\n * 2. Workspace-level configuration\n * 3. Default configuration (lowest priority)\n *\n * The active document is determined by the workspace's activeDocument extension,\n * falling back to the first document if none is specified.\n */\n get config() {\n return mergeObjects<typeof defaultConfig>(\n mergeObjects(defaultConfig, workspaceProps?.config ?? {}),\n documentConfigs[getActiveDocumentName()] ?? {},\n )\n },\n /**\n * Exports the specified document in the requested format.\n *\n * This method serializes the most recently saved local version of the document (from the intermediateDocuments map)\n * to either JSON or YAML. The exported document reflects the last locally saved state, including any edits\n * that have been saved but not yet synced to a remote registry. Runtime/in-memory changes that have not been saved\n * will not be included.\n *\n * @param documentName - The name of the document to export.\n * @param format - The output format: 'json' for a JSON string, or 'yaml' for a YAML string.\n * @returns The document as a string in the requested format, or undefined if the document does not exist.\n *\n * @example\n * // Export a document as JSON\n * const jsonString = store.exportDocument('api', 'json')\n *\n * // Export a document as YAML\n * const yamlString = store.exportDocument('api', 'yaml')\n */\n exportDocument: (documentName: string, format: 'json' | 'yaml') => {\n const intermediateDocument = intermediateDocuments[documentName]\n\n if (!intermediateDocument) {\n return\n }\n\n if (format === 'json') {\n return JSON.stringify(intermediateDocument)\n }\n\n return YAML.stringify(intermediateDocument)\n },\n /**\n * Saves the current state of the specified document to the intermediate documents map.\n *\n * This function captures the latest (reactive) state of the document from the workspace and\n * applies its changes to the corresponding entry in the `intermediateDocuments` map.\n * The `intermediateDocuments` map represents the most recently \"saved\" local version of the document,\n * which may include edits not yet synced to the remote registry.\n *\n * The update is performed in-place. A deep clone of the current document\n * state is used to avoid mutating the reactive object directly.\n *\n * @param documentName - The name of the document to save.\n * @returns An array of diffs that were excluded from being applied (such as changes to ignored keys),\n * or undefined if the document does not exist or cannot be updated.\n *\n * @example\n * // Save the current state of the document named 'api'\n * const excludedDiffs = store.saveDocument('api')\n */\n saveDocument(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n // Obtain the raw state of the current document to ensure accurate diffing\n const updatedDocument = toRaw(getRaw(workspace.documents[documentName]))\n\n // If either the intermediate or updated document is missing, do nothing\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Apply changes from the current document to the intermediate document in place\n const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument)\n return excludedDiffs\n },\n /**\n * Restores the specified document to its last locally saved state.\n *\n * This method updates the current reactive document (in the workspace) with the contents of the\n * corresponding intermediate document (from the `intermediateDocuments` map), effectively discarding\n * any unsaved in-memory changes and reverting to the last saved version.\n * Vue reactivity is preserved by updating the existing reactive object in place.\n *\n * **Warning:** This operation will discard all unsaved (in-memory) changes to the specified document.\n *\n * @param documentName - The name of the document to restore.\n * @returns void\n *\n * @example\n * // Restore the document named 'api' to its last saved state\n * store.revertDocumentChanges('api')\n */\n revertDocumentChanges(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n // Get the raw state of the current document to avoid diffing resolved references.\n // This ensures we update the actual data, not the references.\n // Note: We keep the Vue proxy for reactivity by updating the object in place.\n const updatedDocument = getRaw(workspace.documents[documentName])\n\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Overwrite the current document with the last saved state, discarding unsaved changes.\n applySelectiveUpdates(updatedDocument, intermediateDocument)\n },\n /**\n * Commits the specified document.\n *\n * This method is intended to finalize and persist the current state of the document,\n * potentially syncing it with a remote registry or marking it as the latest committed version.\n *\n * @param documentName - The name of the document to commit.\n * @remarks\n * The actual commit logic is not implemented yet.\n */\n commitDocument(documentName: string) {\n // TODO: Implement commit logic\n console.warn(`Commit operation for document '${documentName}' is not implemented yet.`)\n },\n /**\n * Serializes the current workspace state to a JSON string for backup, persistence, or sharing.\n *\n * This method exports all workspace documents (removing Vue reactivity proxies), workspace metadata,\n * document configurations, and both the original and intermediate document states. The resulting JSON\n * can be imported later to fully restore the workspace to this exact state, including all documents\n * and their configurations.\n *\n * @returns A JSON string representing the complete workspace state.\n */\n exportWorkspace() {\n return JSON.stringify({\n documents: {\n ...Object.fromEntries(\n Object.entries(workspace.documents).map(([name, doc]) => [\n name,\n // Extract the raw document data for export, removing any Vue reactivity wrappers.\n // When importing, the document can be wrapped again in a magic proxy.\n toRaw(getRaw(doc)),\n ]),\n ),\n },\n meta: workspaceProps?.meta ?? {},\n documentConfigs,\n originalDocuments,\n intermediateDocuments,\n } as InMemoryWorkspace)\n },\n /**\n * Imports a workspace from a serialized JSON string.\n *\n * This method parses the input string using the InMemoryWorkspaceSchema,\n * then updates the current workspace state, including documents, metadata,\n * and configuration, with the imported values.\n *\n * @param input - The serialized workspace JSON string to import.\n */\n loadWorkspace(input: string) {\n const result = coerceValue(InMemoryWorkspaceSchema, JSON.parse(input))\n\n // Assign the magic proxy to the documents\n safeAssign(\n workspace.documents,\n Object.fromEntries(Object.entries(result.documents).map(([name, doc]) => [name, createMagicProxy(doc)])),\n )\n\n safeAssign(originalDocuments, result.originalDocuments)\n safeAssign(intermediateDocuments, result.intermediateDocuments)\n safeAssign(documentConfigs, result.documentConfigs)\n safeAssign(workspace, result.meta)\n },\n }\n}\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { generateClientMutators } from '@/mutators'\n"],
|
|
5
|
-
"mappings": "AAAA,
|
|
4
|
+
"sourcesContent": ["import { bundle, upgrade } from '@scalar/openapi-parser'\nimport { fetchUrls } from '@scalar/openapi-parser/plugins-browser'\nimport { reactive, toRaw } from 'vue'\nimport YAML from 'yaml'\n\nimport { applySelectiveUpdates } from '@/helpers/apply-selective-updates'\nimport { deepClone, isObject, safeAssign } from '@/helpers/general'\nimport { getValueByPath } from '@/helpers/json-path-utils'\nimport { mergeObjects } from '@/helpers/merge-object'\nimport { createMagicProxy, getRaw } from '@/helpers/proxy'\nimport { createNavigation, type createNavigationOptions } from '@/navigation'\nimport { extensions } from '@/schemas/extensions'\nimport { type InMemoryWorkspace, InMemoryWorkspaceSchema } from '@/schemas/inmemory-workspace'\nimport { defaultReferenceConfig } from '@/schemas/reference-config'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema } from '@/schemas/v3.1/strict/openapi-document'\nimport type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from '@/schemas/workspace'\nimport type { Config } from '@/schemas/workspace-specification/config'\nimport type { DeepTransform } from '@/types'\n\n/**\n * Input type for workspace document metadata and configuration.\n * This type defines the required and optional fields for initializing a document in the workspace.\n *\n * TODO: merge navigation options with the document config\n */\ntype WorkspaceDocumentMetaInput = {\n /** Optional metadata about the document like title, description, etc */\n meta?: WorkspaceDocumentMeta\n /** Required unique identifier for the document */\n name: string\n /** Optional configuration for generating navigation structure */\n config?: Config & Partial<createNavigationOptions>\n}\n\n/**\n * Represents a document that is loaded from a URL.\n * This type extends WorkspaceDocumentMetaInput to include URL-specific properties.\n */\nexport type UrlDoc = {\n /** URL to fetch the OpenAPI document from */\n url: string\n /** Optional custom fetch implementation to use when retrieving the document. By default the global fetch implementation will be used */\n fetch?: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n} & WorkspaceDocumentMetaInput\n\n/** Represents a document that is provided directly as an object rather than loaded from a URL */\nexport type ObjectDoc = {\n /** The OpenAPI document object containing the API specification */\n document: Record<string, unknown>\n} & WorkspaceDocumentMetaInput\n\n/**\n * Union type representing the possible input formats for a workspace document:\n * - UrlDoc: Document loaded from a URL with optional fetch configuration\n * - ObjectDoc: Direct document object with metadata\n */\nexport type WorkspaceDocumentInput = UrlDoc | ObjectDoc\n\nconst defaultConfig: DeepTransform<Config, 'NonNullable'> = {\n 'x-scalar-reference-config': defaultReferenceConfig,\n}\n\n/**\n * Resolves a workspace document from various input sources (URL, local file, or direct document object).\n *\n * @param workspaceDocument - The document input to resolve, which can be:\n * - A URL to fetch the document from\n * - A direct document object\n * @returns A promise that resolves to an object containing:\n * - ok: boolean indicating if the resolution was successful\n * - data: The resolved document data\n *\n * @example\n * // Resolve from URL\n * const urlDoc = await loadDocument({ name: 'api', url: 'https://api.example.com/openapi.json' })\n *\n * // Resolve direct document\n * const directDoc = await loadDocument({\n * name: 'inline',\n * document: { openapi: '3.0.0', paths: {} }\n * })\n */\nasync function loadDocument(workspaceDocument: WorkspaceDocumentInput) {\n if ('url' in workspaceDocument) {\n return fetchUrls({ fetch: workspaceDocument.fetch }).exec(workspaceDocument.url)\n }\n\n return {\n ok: true as const,\n data: workspaceDocument.document,\n }\n}\n\n/**\n * Configuration object for initializing a workspace store.\n * Defines the initial state and documents for the workspace.\n */\ntype WorkspaceProps = {\n /** Optional metadata for the workspace including theme, active document, etc */\n meta?: WorkspaceMeta\n /** In-mem open api documents. Async source documents (like URLs) can be loaded after initialization */\n documents?: ObjectDoc[]\n /** Workspace configuration */\n config?: Config\n}\n\n/**\n * Type definition for the workspace store return object.\n * This explicit type is needed to avoid TypeScript inference limits.\n *\n * @see https://github.com/microsoft/TypeScript/issues/43817#issuecomment-827746462\n */\nexport type WorkspaceStore = {\n /** Returns the reactive workspace object with an additional activeDocument getter */\n readonly workspace: Workspace\n /** Updates a specific metadata field in the workspace */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]): void\n /** Updates a specific metadata field in a document */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ): void\n /** Resolves a reference in the active document by following the provided path and resolving any external $ref references */\n resolve(path: string[]): Promise<unknown>\n /** Adds a new document to the workspace */\n addDocument(input: WorkspaceDocumentInput): Promise<void>\n /** Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously */\n addDocumentSync(input: ObjectDoc): void\n /** Returns the merged configuration for the active document */\n readonly config: typeof defaultConfig\n /** Downloads the specified document in the requested format */\n exportDocument(documentName: string, format: 'json' | 'yaml'): string | undefined\n /** Persists the current state of the specified document back to the original documents map */\n saveDocument(documentName: string): unknown[] | undefined\n /** Reverts the specified document to its original state */\n revertDocumentChanges(documentName: string): void\n /** Commits the specified document */\n commitDocument(documentName: string): void\n /** Serializes the current workspace state to a JSON string for backup, persistence, or sharing. */\n exportWorkspace(): string\n /** Imports a workspace from a serialized JSON string. */\n loadWorkspace(input: string): void\n}\n\n/**\n * Creates a reactive workspace store that manages documents and their metadata.\n * The store provides functionality for accessing, updating, and resolving document references.\n *\n * @param workspaceProps - Configuration object for the workspace\n * @param workspaceProps.meta - Optional metadata for the workspace\n * @param workspaceProps.documents - Optional record of documents to initialize the workspace with\n * Documents that require asynchronous loading must be added using `addDocument` after the store is created\n * this allows atomic awaiting and does not block page load for the store initialization\n * @returns An object containing methods and getters for managing the workspace\n */\nexport const createWorkspaceStore = (workspaceProps?: WorkspaceProps): WorkspaceStore => {\n /**\n * Holds the original, unmodified documents as they were initially loaded into the workspace.\n * These documents are stored in their raw form\u2014prior to any reactive wrapping, dereferencing, or bundling.\n * This map preserves the pristine structure of each document, using deep clones to ensure that\n * subsequent mutations in the workspace do not affect the originals.\n * The originals are retained so that we can restore, compare, or sync with the remote registry as needed.\n */\n const originalDocuments = {} as Workspace['documents']\n\n /**\n * Stores the intermediate state of documents after local edits but before syncing with the remote registry.\n *\n * This map acts as a local \"saved\" version of the document, reflecting the user's changes after they hit \"save\".\n * The `originalDocuments` map, by contrast, always mirrors the document as it exists in the remote registry.\n *\n * Use this map to stage local changes that are ready to be propagated back to the remote registry.\n * This separation allows us to distinguish between:\n * - The last known remote version (`originalDocuments`)\n * - The latest locally saved version (`intermediateDocuments`)\n * - The current in-memory (possibly unsaved) workspace document (`workspace.documents`)\n */\n const intermediateDocuments = {} as Workspace['documents']\n /**\n * A map of document configurations keyed by document name.\n * This stores the configuration options for each document in the workspace,\n * allowing for document-specific settings like navigation options, appearance,\n * and other reference configuration.\n */\n const documentConfigs: Record<string, Config> = {}\n\n // Create a reactive workspace object with proxied documents\n // Each document is wrapped in a proxy to enable reactive updates and reference resolution\n const workspace = reactive<Workspace>({\n ...workspaceProps?.meta,\n documents: {},\n /**\n * Returns the currently active document from the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The active document or undefined if no document is found\n */\n get activeDocument(): NonNullable<Workspace['activeDocument']> | undefined {\n const activeDocumentKey =\n workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n return workspace.documents[activeDocumentKey]\n },\n })\n\n /**\n * Returns the name of the currently active document in the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The name of the active document or an empty string if no document is found\n */\n function getActiveDocumentName() {\n return workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n }\n\n // Add a document to the store synchronously from an in-memory OpenAPI document\n function addDocumentSync(input: ObjectDoc) {\n const { name, meta } = input\n\n const document = coerceValue(OpenAPIDocumentSchema, upgrade(input.document).specification)\n\n // Store the original document in the originalDocuments map\n // This is used to track the original state of the document as it was loaded into the workspace\n originalDocuments[name] = deepClone({ ...document, ...meta })\n // Store the intermediate document state for local edits\n // This is used to track the last saved state of the document\n // It allows us to differentiate between the original document and the latest saved version\n // This is important for local edits that are not yet synced with the remote registry\n // The intermediate document is used to store the latest saved state of the document\n // This allows us to track changes and revert to the last saved state if needed\n intermediateDocuments[name] = deepClone({ ...document, ...meta })\n // Add the document config to the documentConfigs map\n documentConfigs[name] = input.config ?? {}\n\n // Skip navigation generation if the document already has a server-side generated navigation structure\n if (document[extensions.document.navigation] === undefined) {\n document[extensions.document.navigation] = createNavigation(document, input.config ?? {}).entries\n }\n\n workspace.documents[name] = createMagicProxy({ ...document, ...meta })\n }\n\n // Add any initial documents to the store\n workspaceProps?.documents?.forEach(addDocumentSync)\n\n // Cache to track visited nodes during reference resolution to prevent bundling the same subtree multiple times\n // This is needed because we are doing partial bundle operations\n const visitedNodesCache = new Set()\n\n return {\n /**\n * Returns the reactive workspace object with an additional activeDocument getter\n */\n get workspace() {\n return workspace\n },\n /**\n * Updates a specific metadata field in the workspace\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @example\n * // Update the workspace title\n * update('x-scalar-active-document', 'document-name')\n */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]) {\n // @ts-ignore\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n throw new Error('Invalid key: cannot modify prototype')\n }\n Object.assign(workspace, { [key]: value })\n },\n /**\n * Updates a specific metadata field in a document\n * @param name - The name of the document to update ('active' or a specific document name)\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @throws Error if the specified document doesn't exist\n * @example\n * // Update the auth of the active document\n * updateDocument('active', 'x-scalar-active-auth', 'Bearer')\n * // Update the auth of a specific document\n * updateDocument('document-name', 'x-scalar-active-auth', 'Bearer')\n */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ) {\n const currentDocument = workspace.documents[name === 'active' ? getActiveDocumentName() : name]\n\n if (!currentDocument) {\n throw 'Please select a valid document'\n }\n\n Object.assign(currentDocument, { [key]: value })\n },\n /**\n * Resolves a reference in the active document by following the provided path and resolving any external $ref references.\n * This method traverses the document structure following the given path and resolves any $ref references it encounters.\n * During resolution, it sets a loading status and updates the reference with the resolved content.\n *\n * @param path - Array of strings representing the path to the reference (e.g. ['paths', '/users', 'get', 'responses', '200'])\n * @throws Error if the path is invalid or empty\n * @example\n * // Resolve a reference in the active document\n * resolve(['paths', '/users', 'get', 'responses', '200'])\n */\n resolve: async (path: string[]) => {\n const activeDocument = workspace.activeDocument\n\n const target = getValueByPath(activeDocument, path)\n\n if (!isObject(target)) {\n console.error(\n `Invalid path provided for resolution. Path: [${path.join(', ')}]. Found value of type: ${typeof target}. Expected an object.`,\n )\n return\n }\n\n // Bundle the target document with the active document as root, resolving any external references\n // and tracking resolution status through hooks\n return bundle(target, {\n root: activeDocument,\n treeShake: false,\n plugins: [fetchUrls()],\n urlMap: false,\n hooks: {\n onResolveStart: (node) => {\n node['$status'] = 'loading'\n },\n onResolveError: (node) => {\n node['$status'] = 'error'\n },\n },\n visitedNodes: visitedNodesCache,\n })\n },\n /**\n * Adds a new document to the workspace\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocument: async (input: WorkspaceDocumentInput) => {\n const { name, meta, config } = input\n\n const resolve = await loadDocument(input)\n\n if (!resolve.ok) {\n console.error(`Failed to fetch document '${name}': request was not successful`)\n\n workspace.documents[name] = {\n ...meta,\n openapi: '3.1.0',\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n }\n\n return\n }\n\n if (!isObject(resolve.data)) {\n console.error(`Failed to load document '${name}': response data is not a valid object`)\n\n workspace.documents[name] = {\n ...meta,\n openapi: '3.1.0',\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n }\n\n return\n }\n\n addDocumentSync({ document: resolve.data, name, meta, config })\n },\n /**\n * Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocumentSync,\n /**\n * Returns the merged configuration for the active document.\n *\n * This getter merges configurations in the following order of precedence:\n * 1. Document-specific configuration (highest priority)\n * 2. Workspace-level configuration\n * 3. Default configuration (lowest priority)\n *\n * The active document is determined by the workspace's activeDocument extension,\n * falling back to the first document if none is specified.\n */\n get config() {\n return mergeObjects<typeof defaultConfig>(\n mergeObjects(defaultConfig, workspaceProps?.config ?? {}),\n documentConfigs[getActiveDocumentName()] ?? {},\n )\n },\n /**\n * Exports the specified document in the requested format.\n *\n * This method serializes the most recently saved local version of the document (from the intermediateDocuments map)\n * to either JSON or YAML. The exported document reflects the last locally saved state, including any edits\n * that have been saved but not yet synced to a remote registry. Runtime/in-memory changes that have not been saved\n * will not be included.\n *\n * @param documentName - The name of the document to export.\n * @param format - The output format: 'json' for a JSON string, or 'yaml' for a YAML string.\n * @returns The document as a string in the requested format, or undefined if the document does not exist.\n *\n * @example\n * // Export a document as JSON\n * const jsonString = store.exportDocument('api', 'json')\n *\n * // Export a document as YAML\n * const yamlString = store.exportDocument('api', 'yaml')\n */\n exportDocument: (documentName: string, format: 'json' | 'yaml') => {\n const intermediateDocument = intermediateDocuments[documentName]\n\n if (!intermediateDocument) {\n return\n }\n\n if (format === 'json') {\n return JSON.stringify(intermediateDocument)\n }\n\n return YAML.stringify(intermediateDocument)\n },\n /**\n * Saves the current state of the specified document to the intermediate documents map.\n *\n * This function captures the latest (reactive) state of the document from the workspace and\n * applies its changes to the corresponding entry in the `intermediateDocuments` map.\n * The `intermediateDocuments` map represents the most recently \"saved\" local version of the document,\n * which may include edits not yet synced to the remote registry.\n *\n * The update is performed in-place. A deep clone of the current document\n * state is used to avoid mutating the reactive object directly.\n *\n * @param documentName - The name of the document to save.\n * @returns An array of diffs that were excluded from being applied (such as changes to ignored keys),\n * or undefined if the document does not exist or cannot be updated.\n *\n * @example\n * // Save the current state of the document named 'api'\n * const excludedDiffs = store.saveDocument('api')\n */\n saveDocument(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n // Obtain the raw state of the current document to ensure accurate diffing\n const updatedDocument = toRaw(getRaw(workspace.documents[documentName]))\n\n // If either the intermediate or updated document is missing, do nothing\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Apply changes from the current document to the intermediate document in place\n const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument)\n return excludedDiffs\n },\n /**\n * Restores the specified document to its last locally saved state.\n *\n * This method updates the current reactive document (in the workspace) with the contents of the\n * corresponding intermediate document (from the `intermediateDocuments` map), effectively discarding\n * any unsaved in-memory changes and reverting to the last saved version.\n * Vue reactivity is preserved by updating the existing reactive object in place.\n *\n * **Warning:** This operation will discard all unsaved (in-memory) changes to the specified document.\n *\n * @param documentName - The name of the document to restore.\n * @returns void\n *\n * @example\n * // Restore the document named 'api' to its last saved state\n * store.revertDocumentChanges('api')\n */\n revertDocumentChanges(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n // Get the raw state of the current document to avoid diffing resolved references.\n // This ensures we update the actual data, not the references.\n // Note: We keep the Vue proxy for reactivity by updating the object in place.\n const updatedDocument = getRaw(workspace.documents[documentName])\n\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Overwrite the current document with the last saved state, discarding unsaved changes.\n applySelectiveUpdates(updatedDocument, intermediateDocument)\n },\n /**\n * Commits the specified document.\n *\n * This method is intended to finalize and persist the current state of the document,\n * potentially syncing it with a remote registry or marking it as the latest committed version.\n *\n * @param documentName - The name of the document to commit.\n * @remarks\n * The actual commit logic is not implemented yet.\n */\n commitDocument(documentName: string) {\n // TODO: Implement commit logic\n console.warn(`Commit operation for document '${documentName}' is not implemented yet.`)\n },\n /**\n * Serializes the current workspace state to a JSON string for backup, persistence, or sharing.\n *\n * This method exports all workspace documents (removing Vue reactivity proxies), workspace metadata,\n * document configurations, and both the original and intermediate document states. The resulting JSON\n * can be imported later to fully restore the workspace to this exact state, including all documents\n * and their configurations.\n *\n * @returns A JSON string representing the complete workspace state.\n */\n exportWorkspace() {\n return JSON.stringify({\n documents: {\n ...Object.fromEntries(\n Object.entries(workspace.documents).map(([name, doc]) => [\n name,\n // Extract the raw document data for export, removing any Vue reactivity wrappers.\n // When importing, the document can be wrapped again in a magic proxy.\n toRaw(getRaw(doc)),\n ]),\n ),\n },\n meta: workspaceProps?.meta ?? {},\n documentConfigs,\n originalDocuments,\n intermediateDocuments,\n } as InMemoryWorkspace)\n },\n /**\n * Imports a workspace from a serialized JSON string.\n *\n * This method parses the input string using the InMemoryWorkspaceSchema,\n * then updates the current workspace state, including documents, metadata,\n * and configuration, with the imported values.\n *\n * @param input - The serialized workspace JSON string to import.\n */\n loadWorkspace(input: string) {\n const result = coerceValue(InMemoryWorkspaceSchema, JSON.parse(input))\n\n // Assign the magic proxy to the documents\n safeAssign(\n workspace.documents,\n Object.fromEntries(Object.entries(result.documents).map(([name, doc]) => [name, createMagicProxy(doc)])),\n )\n\n safeAssign(originalDocuments, result.originalDocuments)\n safeAssign(intermediateDocuments, result.intermediateDocuments)\n safeAssign(documentConfigs, result.documentConfigs)\n safeAssign(workspace, result.meta)\n },\n }\n}\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { generateClientMutators } from '@/mutators'\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,QAAQ,eAAe;AAChC,SAAS,iBAAiB;AAC1B,SAAS,UAAU,aAAa;AAChC,OAAO,UAAU;AAEjB,SAAS,6BAA6B;AACtC,SAAS,WAAW,UAAU,kBAAkB;AAChD,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB,cAAc;AACzC,SAAS,wBAAsD;AAC/D,SAAS,kBAAkB;AAC3B,SAAiC,+BAA+B;AAChE,SAAS,8BAA8B;AACvC,SAAS,mBAAmB;AAC5B,SAAS,6BAA6B;AA4CtC,MAAM,gBAAsD;AAAA,EAC1D,6BAA6B;AAC/B;AAsBA,eAAe,aAAa,mBAA2C;AACrE,MAAI,SAAS,mBAAmB;AAC9B,WAAO,UAAU,EAAE,OAAO,kBAAkB,MAAM,CAAC,EAAE,KAAK,kBAAkB,GAAG;AAAA,EACjF;AAEA,SAAO;A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,OAAO;AAAA,YACR,OAAO,QAAQ,UAAU,SAAS,EAAE,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM;AAAA,cACvD;AAAA;AAAA;AAAA,cAGA,MAAM,OAAO,GAAG,CAAC;AAAA,YACnB,CAAC;AAAA,UACH;AAAA,QACF;AAAA,QACA,MAAM,gBAAgB,QAAQ,CAAC;AAAA,QAC/B;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAsB;AAAA,IACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAUA,cAAc,OAAe;AAC3B,YAAM,SAAS,YAAY,yBAAyB,KAAK,MAAM,KAAK,CAAC;AAGrE;AAAA,QACE,UAAU;AAAA,QACV,OAAO,YAAY,OAAO,QAAQ,OAAO,SAAS,EAAE,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,CAAC;AAAA,MACzG;AAEA,iBAAW,mBAAmB,OAAO,iBAAiB;AACtD,iBAAW,uBAAuB,OAAO,qBAAqB;AAC9D,iBAAW,iBAAiB,OAAO,eAAe;AAClD,iBAAW,WAAW,OAAO,IAAI;AAAA,IACnC;AAAA,EACF;AACF;AAGA,SAAS,8BAA8B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/helpers/proxy.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ export declare const TARGET_SYMBOL: unique symbol;
|
|
|
48
48
|
* // proxy1 and proxy2 are the same instance due to caching
|
|
49
49
|
* console.log(proxy1 === proxy2) // true
|
|
50
50
|
*/
|
|
51
|
-
export declare function createMagicProxy<T extends UnknownObject>(targetObject: T, sourceDocument?: T, resolvedProxyCache?: WeakMap<object, T>): T;
|
|
51
|
+
export declare function createMagicProxy<T extends UnknownObject | UnknownObject[]>(targetObject: T, sourceDocument?: T, resolvedProxyCache?: WeakMap<object, T>): T;
|
|
52
52
|
/**
|
|
53
53
|
* Gets the raw (non-proxied) version of an object created by createMagicProxy.
|
|
54
54
|
* This is useful when you need to access the original object without the magic proxy wrapper.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../src/helpers/proxy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAE9C,eAAO,MAAM,aAAa,eAAmB,CAAA;AAyH7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,aAAa,
|
|
1
|
+
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../src/helpers/proxy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAE9C,eAAO,MAAM,aAAa,eAAmB,CAAA;AAyH7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,aAAa,GAAG,aAAa,EAAE,EACxE,YAAY,EAAE,CAAC,EACf,cAAc,GAAE,CAAgB,EAChC,kBAAkB,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,GACtC,CAAC,CAyBH;AAED;;;;;;;;;GASG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,aAAa,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAEzD"}
|
package/dist/helpers/proxy.js
CHANGED
|
@@ -13,7 +13,7 @@ function createProxyHandler(sourceDocument, resolvedProxyCache) {
|
|
|
13
13
|
}
|
|
14
14
|
const value = Reflect.get(target, property, receiver);
|
|
15
15
|
const deepResolveNestedRefs = (value2, originalRef) => {
|
|
16
|
-
if (!isObject(value2)) {
|
|
16
|
+
if (!isObject(value2) && !Array.isArray(value2)) {
|
|
17
17
|
return value2;
|
|
18
18
|
}
|
|
19
19
|
if ("$ref" in value2) {
|
|
@@ -75,7 +75,7 @@ function createProxyHandler(sourceDocument, resolvedProxyCache) {
|
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
function createMagicProxy(targetObject, sourceDocument = targetObject, resolvedProxyCache) {
|
|
78
|
-
if (!isObject(targetObject)) {
|
|
78
|
+
if (!isObject(targetObject) && !Array.isArray(targetObject)) {
|
|
79
79
|
return targetObject;
|
|
80
80
|
}
|
|
81
81
|
const rawTarget = isReactive(targetObject) ? toRaw(targetObject) : targetObject;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/helpers/proxy.ts"],
|
|
4
|
-
"sourcesContent": ["import { isReactive, toRaw } from 'vue'\nimport { getValueByPath, parseJsonPointer } from './json-path-utils'\nimport { isLocalRef, isObject } from './general'\nimport type { UnknownObject } from './general'\n\nexport const TARGET_SYMBOL = Symbol('target')\n\n/**\n * Creates a proxy handler that automatically resolves JSON references ($ref) in an object.\n * The handler intercepts property access, assignment, and property enumeration to automatically\n * resolve any $ref references to their target values in the source document.\n *\n * @param sourceDocument - The source document containing the reference targets\n * @param resolvedProxyCache - Optional cache to store resolved proxies and prevent duplicate proxies\n * @returns A proxy handler that automatically resolves $ref references\n */\nfunction createProxyHandler(\n sourceDocument: UnknownObject,\n resolvedProxyCache?: WeakMap<object, UnknownObject>,\n): ProxyHandler<UnknownObject> {\n return {\n get(target, property, receiver) {\n if (property === TARGET_SYMBOL) {\n return target\n }\n\n if (property === '__isProxy') {\n return true\n }\n\n const value = Reflect.get(target, property, receiver)\n\n /**\n * Recursively resolves nested references in an object.\n * If the value is not an object, returns it as is.\n * If the value has a $ref property:\n * - For local references: resolves the reference and continues resolving nested refs\n * - For all other objects: creates a proxy for lazy resolution\n */\n const deepResolveNestedRefs = (value: unknown, originalRef?: string) => {\n if (!isObject(value)) {\n return value\n }\n\n if ('$ref' in value) {\n const ref = value.$ref as string\n\n if (isLocalRef(ref)) {\n const referencePath = parseJsonPointer(ref)\n const resolvedValue = getValueByPath(sourceDocument, referencePath)\n\n // preserve the first $ref to maintain the original reference\n return deepResolveNestedRefs(resolvedValue, originalRef ?? ref)\n }\n }\n\n if (originalRef) {\n return createMagicProxy({ ...value, 'x-original-ref': originalRef }, sourceDocument, resolvedProxyCache)\n }\n\n return createMagicProxy(value, sourceDocument, resolvedProxyCache)\n }\n\n return deepResolveNestedRefs(value)\n },\n\n set(target: UnknownObject, property: string, newValue: unknown, receiver: UnknownObject) {\n const rawTarget = isReactive(target) ? toRaw(target) : target\n const currentValue = rawTarget[property]\n\n if (\n isObject(currentValue) &&\n '$ref' in currentValue &&\n typeof currentValue.$ref === 'string' &&\n isLocalRef(currentValue.$ref)\n ) {\n const referencePath = parseJsonPointer(currentValue.$ref)\n const targetObject = getValueByPath(sourceDocument, referencePath.slice(0, -1)) as UnknownObject\n const lastPathSegment = referencePath[referencePath.length - 1]\n\n if (targetObject && lastPathSegment) {\n targetObject[lastPathSegment] = newValue\n }\n } else {\n Reflect.set(rawTarget, property, newValue, receiver)\n }\n return true\n },\n\n has(target: UnknownObject, key: string) {\n if (typeof key === 'string' && key !== '$ref' && typeof target.$ref === 'string' && isLocalRef(target.$ref)) {\n const referencePath = parseJsonPointer(target['$ref'])\n const resolvedValue = getValueByPath(sourceDocument, referencePath) as UnknownObject\n\n return resolvedValue ? key in resolvedValue : false\n }\n\n return key in target\n },\n\n ownKeys(target: UnknownObject) {\n if ('$ref' in target && typeof target.$ref === 'string' && isLocalRef(target.$ref)) {\n const referencePath = parseJsonPointer(target['$ref'])\n const resolvedValue = getValueByPath(sourceDocument, referencePath)\n\n return resolvedValue ? Reflect.ownKeys(resolvedValue) : []\n }\n\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target: UnknownObject, key: string) {\n if ('$ref' in target && key !== '$ref' && typeof target.$ref === 'string' && isLocalRef(target.$ref)) {\n const referencePath = parseJsonPointer(target['$ref'])\n const resolvedValue = getValueByPath(sourceDocument, referencePath)\n\n if (resolvedValue) {\n return Object.getOwnPropertyDescriptor(resolvedValue, key)\n }\n }\n\n return Object.getOwnPropertyDescriptor(target, key)\n },\n }\n}\n\n/**\n * Creates a proxy that automatically resolves JSON references ($ref) in an object.\n * The proxy intercepts property access and automatically resolves any $ref references\n * to their target values in the source document.\n *\n * @param targetObject - The object to create a proxy for\n * @param sourceDocument - The source document containing the reference targets (defaults to targetObject)\n * @param resolvedProxyCache - Optional cache to store resolved proxies and prevent duplicate proxies\n * @returns A proxy that automatically resolves $ref references\n *\n * @example\n * // Basic usage with local references\n * const doc = {\n * components: {\n * schemas: {\n * User: { type: 'object', properties: { name: { type: 'string' } } }\n * }\n * },\n * paths: {\n * '/users': {\n * get: {\n * responses: {\n * 200: {\n * content: {\n * 'application/json': {\n * schema: { $ref: '#/components/schemas/User' }\n * }\n * }\n * }\n * }\n * }\n * }\n * }\n * }\n *\n * const proxy = createMagicProxy(doc)\n * // Accessing the schema will automatically resolve the $ref\n * console.log(proxy.paths['/users'].get.responses[200].content['application/json'].schema)\n * // Output: { type: 'object', properties: { name: { type: 'string' } } }\n *\n * @example\n * // Using with a cache to prevent duplicate proxies\n * const cache = new WeakMap()\n * const proxy1 = createMagicProxy(doc, doc, cache)\n * const proxy2 = createMagicProxy(doc, doc, cache)\n * // proxy1 and proxy2 are the same instance due to caching\n * console.log(proxy1 === proxy2) // true\n */\nexport function createMagicProxy<T extends UnknownObject>(\n targetObject: T,\n sourceDocument: T = targetObject,\n resolvedProxyCache?: WeakMap<object, T>,\n): T {\n if (!isObject(targetObject)) {\n return targetObject\n }\n\n const rawTarget = isReactive(targetObject) ? toRaw(targetObject) : targetObject\n\n // check for cached results\n if (resolvedProxyCache?.has(rawTarget)) {\n const cachedValue = resolvedProxyCache.get(rawTarget)\n\n if (cachedValue) {\n return cachedValue\n }\n }\n\n // Create a handler with the correct context\n const handler = createProxyHandler(sourceDocument, resolvedProxyCache)\n const proxy = new Proxy<T>(rawTarget, handler)\n\n if (resolvedProxyCache) {\n resolvedProxyCache.set(rawTarget, proxy)\n }\n\n return proxy\n}\n\n/**\n * Gets the raw (non-proxied) version of an object created by createMagicProxy.\n * This is useful when you need to access the original object without the magic proxy wrapper.\n *\n * @param obj - The magic proxy object to get the raw version of\n * @returns The raw version of the object\n * @example\n * const proxy = createMagicProxy({ foo: { $ref: '#/bar' } })\n * const raw = getRaw(proxy) // { foo: { $ref: '#/bar' } }\n */\nexport function getRaw<T extends UnknownObject>(obj: T): T {\n return (obj as T & { [TARGET_SYMBOL]: T })[TARGET_SYMBOL]\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,YAAY,aAAa;AAClC,SAAS,gBAAgB,wBAAwB;AACjD,SAAS,YAAY,gBAAgB;AAG9B,MAAM,gBAAgB,OAAO,QAAQ;AAW5C,SAAS,mBACP,gBACA,
|
|
4
|
+
"sourcesContent": ["import { isReactive, toRaw } from 'vue'\nimport { getValueByPath, parseJsonPointer } from './json-path-utils'\nimport { isLocalRef, isObject } from './general'\nimport type { UnknownObject } from './general'\n\nexport const TARGET_SYMBOL = Symbol('target')\n\n/**\n * Creates a proxy handler that automatically resolves JSON references ($ref) in an object.\n * The handler intercepts property access, assignment, and property enumeration to automatically\n * resolve any $ref references to their target values in the source document.\n *\n * @param sourceDocument - The source document containing the reference targets\n * @param resolvedProxyCache - Optional cache to store resolved proxies and prevent duplicate proxies\n * @returns A proxy handler that automatically resolves $ref references\n */\nfunction createProxyHandler(\n sourceDocument: UnknownObject | UnknownObject[],\n resolvedProxyCache?: WeakMap<object, UnknownObject | UnknownObject[]>,\n): ProxyHandler<UnknownObject | UnknownObject[]> {\n return {\n get(target, property, receiver) {\n if (property === TARGET_SYMBOL) {\n return target\n }\n\n if (property === '__isProxy') {\n return true\n }\n\n const value = Reflect.get(target, property, receiver)\n\n /**\n * Recursively resolves nested references in an object.\n * If the value is not an object, returns it as is.\n * If the value has a $ref property:\n * - For local references: resolves the reference and continues resolving nested refs\n * - For all other objects: creates a proxy for lazy resolution\n */\n const deepResolveNestedRefs = (value: unknown, originalRef?: string) => {\n if (!isObject(value) && !Array.isArray(value)) {\n return value\n }\n\n if ('$ref' in value) {\n const ref = value.$ref as string\n\n if (isLocalRef(ref)) {\n const referencePath = parseJsonPointer(ref)\n const resolvedValue = getValueByPath(sourceDocument, referencePath)\n\n // preserve the first $ref to maintain the original reference\n return deepResolveNestedRefs(resolvedValue, originalRef ?? ref)\n }\n }\n\n if (originalRef) {\n return createMagicProxy({ ...value, 'x-original-ref': originalRef }, sourceDocument, resolvedProxyCache)\n }\n\n return createMagicProxy(value, sourceDocument, resolvedProxyCache)\n }\n\n return deepResolveNestedRefs(value)\n },\n\n set(target: UnknownObject, property: string, newValue: unknown, receiver: UnknownObject) {\n const rawTarget = isReactive(target) ? toRaw(target) : target\n const currentValue = rawTarget[property]\n\n if (\n isObject(currentValue) &&\n '$ref' in currentValue &&\n typeof currentValue.$ref === 'string' &&\n isLocalRef(currentValue.$ref)\n ) {\n const referencePath = parseJsonPointer(currentValue.$ref)\n const targetObject = getValueByPath(sourceDocument, referencePath.slice(0, -1)) as UnknownObject\n const lastPathSegment = referencePath[referencePath.length - 1]\n\n if (targetObject && lastPathSegment) {\n targetObject[lastPathSegment] = newValue\n }\n } else {\n Reflect.set(rawTarget, property, newValue, receiver)\n }\n return true\n },\n\n has(target: UnknownObject, key: string) {\n if (typeof key === 'string' && key !== '$ref' && typeof target.$ref === 'string' && isLocalRef(target.$ref)) {\n const referencePath = parseJsonPointer(target['$ref'])\n const resolvedValue = getValueByPath(sourceDocument, referencePath) as UnknownObject\n\n return resolvedValue ? key in resolvedValue : false\n }\n\n return key in target\n },\n\n ownKeys(target: UnknownObject) {\n if ('$ref' in target && typeof target.$ref === 'string' && isLocalRef(target.$ref)) {\n const referencePath = parseJsonPointer(target['$ref'])\n const resolvedValue = getValueByPath(sourceDocument, referencePath)\n\n return resolvedValue ? Reflect.ownKeys(resolvedValue) : []\n }\n\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target: UnknownObject, key: string) {\n if ('$ref' in target && key !== '$ref' && typeof target.$ref === 'string' && isLocalRef(target.$ref)) {\n const referencePath = parseJsonPointer(target['$ref'])\n const resolvedValue = getValueByPath(sourceDocument, referencePath)\n\n if (resolvedValue) {\n return Object.getOwnPropertyDescriptor(resolvedValue, key)\n }\n }\n\n return Object.getOwnPropertyDescriptor(target, key)\n },\n }\n}\n\n/**\n * Creates a proxy that automatically resolves JSON references ($ref) in an object.\n * The proxy intercepts property access and automatically resolves any $ref references\n * to their target values in the source document.\n *\n * @param targetObject - The object to create a proxy for\n * @param sourceDocument - The source document containing the reference targets (defaults to targetObject)\n * @param resolvedProxyCache - Optional cache to store resolved proxies and prevent duplicate proxies\n * @returns A proxy that automatically resolves $ref references\n *\n * @example\n * // Basic usage with local references\n * const doc = {\n * components: {\n * schemas: {\n * User: { type: 'object', properties: { name: { type: 'string' } } }\n * }\n * },\n * paths: {\n * '/users': {\n * get: {\n * responses: {\n * 200: {\n * content: {\n * 'application/json': {\n * schema: { $ref: '#/components/schemas/User' }\n * }\n * }\n * }\n * }\n * }\n * }\n * }\n * }\n *\n * const proxy = createMagicProxy(doc)\n * // Accessing the schema will automatically resolve the $ref\n * console.log(proxy.paths['/users'].get.responses[200].content['application/json'].schema)\n * // Output: { type: 'object', properties: { name: { type: 'string' } } }\n *\n * @example\n * // Using with a cache to prevent duplicate proxies\n * const cache = new WeakMap()\n * const proxy1 = createMagicProxy(doc, doc, cache)\n * const proxy2 = createMagicProxy(doc, doc, cache)\n * // proxy1 and proxy2 are the same instance due to caching\n * console.log(proxy1 === proxy2) // true\n */\nexport function createMagicProxy<T extends UnknownObject | UnknownObject[]>(\n targetObject: T,\n sourceDocument: T = targetObject,\n resolvedProxyCache?: WeakMap<object, T>,\n): T {\n if (!isObject(targetObject) && !Array.isArray(targetObject)) {\n return targetObject\n }\n\n const rawTarget = isReactive(targetObject) ? toRaw(targetObject) : targetObject\n\n // check for cached results\n if (resolvedProxyCache?.has(rawTarget)) {\n const cachedValue = resolvedProxyCache.get(rawTarget)\n\n if (cachedValue) {\n return cachedValue\n }\n }\n\n // Create a handler with the correct context\n const handler = createProxyHandler(sourceDocument, resolvedProxyCache)\n const proxy = new Proxy<T>(rawTarget, handler)\n\n if (resolvedProxyCache) {\n resolvedProxyCache.set(rawTarget, proxy)\n }\n\n return proxy\n}\n\n/**\n * Gets the raw (non-proxied) version of an object created by createMagicProxy.\n * This is useful when you need to access the original object without the magic proxy wrapper.\n *\n * @param obj - The magic proxy object to get the raw version of\n * @returns The raw version of the object\n * @example\n * const proxy = createMagicProxy({ foo: { $ref: '#/bar' } })\n * const raw = getRaw(proxy) // { foo: { $ref: '#/bar' } }\n */\nexport function getRaw<T extends UnknownObject>(obj: T): T {\n return (obj as T & { [TARGET_SYMBOL]: T })[TARGET_SYMBOL]\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,YAAY,aAAa;AAClC,SAAS,gBAAgB,wBAAwB;AACjD,SAAS,YAAY,gBAAgB;AAG9B,MAAM,gBAAgB,OAAO,QAAQ;AAW5C,SAAS,mBACP,gBACA,oBAC+C;AAC/C,SAAO;AAAA,IACL,IAAI,QAAQ,UAAU,UAAU;AAC9B,UAAI,aAAa,eAAe;AAC9B,eAAO;AAAA,MACT;AAEA,UAAI,aAAa,aAAa;AAC5B,eAAO;AAAA,MACT;AAEA,YAAM,QAAQ,QAAQ,IAAI,QAAQ,UAAU,QAAQ;AASpD,YAAM,wBAAwB,CAACA,QAAgB,gBAAyB;AACtE,YAAI,CAAC,SAASA,MAAK,KAAK,CAAC,MAAM,QAAQA,MAAK,GAAG;AAC7C,iBAAOA;AAAA,QACT;AAEA,YAAI,UAAUA,QAAO;AACnB,gBAAM,MAAMA,OAAM;AAElB,cAAI,WAAW,GAAG,GAAG;AACnB,kBAAM,gBAAgB,iBAAiB,GAAG;AAC1C,kBAAM,gBAAgB,eAAe,gBAAgB,aAAa;AAGlE,mBAAO,sBAAsB,eAAe,eAAe,GA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