@bjornharrtell/json-api 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs/enums/RelationshipType.html +2 -2
- package/dist/docs/functions/camel.html +1 -1
- package/dist/docs/functions/useJsonApi.html +1 -1
- package/dist/docs/interfaces/AtomicOperation.html +2 -2
- package/dist/docs/interfaces/BaseEntity.html +2 -2
- package/dist/docs/interfaces/FetchOptions.html +2 -2
- package/dist/docs/interfaces/FetchParams.html +1 -1
- package/dist/docs/interfaces/JsonApiAtomicDocument.html +2 -2
- package/dist/docs/interfaces/JsonApiAtomicOperation.html +2 -2
- package/dist/docs/interfaces/JsonApiAtomicResult.html +2 -2
- package/dist/docs/interfaces/JsonApiConfig.html +4 -4
- package/dist/docs/interfaces/JsonApiDocument.html +2 -2
- package/dist/docs/interfaces/JsonApiError.html +2 -2
- package/dist/docs/interfaces/JsonApiLinkObject.html +2 -2
- package/dist/docs/interfaces/JsonApiLinks.html +2 -2
- package/dist/docs/interfaces/JsonApiMeta.html +2 -2
- package/dist/docs/interfaces/JsonApiRelationship.html +2 -2
- package/dist/docs/interfaces/JsonApiResource.html +2 -2
- package/dist/docs/interfaces/JsonApiResourceIdentifier.html +2 -2
- package/dist/docs/interfaces/ModelDefinition.html +3 -3
- package/dist/docs/interfaces/PageOption.html +2 -2
- package/dist/docs/interfaces/Relationship.html +3 -3
- package/dist/docs/types/JsonApi.html +1 -1
- package/dist/docs/types/JsonApiFetcher.html +1 -1
- package/dist/docs/types/JsonApiLink.html +1 -1
- package/dist/lib.d.ts +1 -1
- package/dist/lib.js +174 -159
- package/dist/lib.js.map +1 -1
- package/package.json +1 -1
package/dist/lib.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api.ts"],"sourcesContent":["import type { JsonApiAtomicDocument, JsonApiDocument, JsonApiResource } from './json-api.ts'\n\nfunction resolvePath(...segments: string[]): string {\n return new URL(segments.join('/')).href\n}\n\nexport interface PageOption {\n size?: number\n number?: number\n}\n\nexport interface FetchOptions {\n fields?: Record<string, string[]>\n page?: PageOption\n include?: string[]\n filter?: string\n headers?: HeadersInit\n body?: BodyInit\n signal?: AbortSignal\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface Options {\n searchParams?: URLSearchParams\n headers: Headers\n method?: string\n body?: BodyInit\n signal?: AbortSignal\n}\n\nasync function req(url: string, options: Options) {\n const { headers, searchParams, method, signal, body } = options\n const textSearchParams = searchParams ? `?${searchParams}` : ''\n const finalUrl = url.replace(/(?:\\?.*?)?(?=#|$)/, textSearchParams)\n const response = await fetch(finalUrl, {\n method,\n headers,\n signal,\n body,\n })\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)\n const data = (await response.json()) as JsonApiDocument\n return data\n}\n\nasync function postAtomic(url: string, options: FetchOptions) {\n const { signal, body } = options\n const method = 'POST'\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n headers.append('Content-Type', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n const response = await fetch(url, {\n method,\n headers,\n signal,\n body,\n })\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)\n if (response.status === 204) return\n const data = (await response.json()) as JsonApiAtomicDocument\n return data\n}\n\nexport type JsonApiFetcher = InstanceType<typeof JsonApiFetcherImpl>\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(public endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, body?: BodyInit): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json')\n const requestOptions = { searchParams, headers, body }\n if (options.fields)\n for (const [key, value] of Object.entries(options.fields)) searchParams.append(`fields[${key}]`, value.join(','))\n if (options.page?.size) searchParams.append('page[size]', options.page.size.toString())\n if (options.page?.number) searchParams.append('page[number]', options.page.number.toString())\n if (options.include) searchParams.append('include', options.include.join(','))\n if (options.filter) searchParams.append('filter', options.filter)\n for (const [key, value] of Object.entries(params)) searchParams.append(key, value)\n return requestOptions\n }\n async fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams) {\n const segments = [this.endpoint, type]\n if (id) segments.push(id)\n const url = resolvePath(...segments)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await req(url, this.createOptions(options, params))\n const resources = doc.data as JsonApiResource[]\n return resources\n }\n async fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id)\n const doc = await req(url, this.createOptions(options, params))\n const resource = doc.data as JsonApiResource\n return resource\n }\n async fetchHasMany(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchBelongsTo(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async post(resource: JsonApiResource, options?: FetchOptions) {\n const url = resolvePath(this.endpoint, resource.type)\n const postDoc: JsonApiDocument = {\n data: resource,\n }\n const body = JSON.stringify(postDoc)\n const newOptions = this.createOptions(options, {}, body)\n newOptions.method = 'POST'\n newOptions.headers.set('Content-Type', 'application/vnd.api+json')\n const doc = (await req(url, newOptions)) as JsonApiDocument\n return doc\n }\n async postAtomic(doc: JsonApiAtomicDocument, options: FetchOptions = {}) {\n const url = new URL([this.endpoint, 'operations'].join('/')).href\n options.body = JSON.stringify(doc)\n const results = await postAtomic(url, options)\n return results\n }\n}\n","/**\n * Convert str from kebab-case to camelCase\n */\nexport function camel(str: string) {\n return str.replace(/[-][a-z\\u00E0-\\u00F6\\u00F8-\\u00FE]/g, (match) => match.slice(1).toUpperCase())\n}\n","import { type FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher.ts'\nimport { camel } from './util.ts'\n\nexport interface JsonApiResourceIdentifier {\n id?: string\n lid?: string\n type: string\n}\n\nexport interface JsonApiRelationship {\n data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[]\n}\n\nexport interface JsonApiResource {\n id?: string\n lid?: string\n type: string\n attributes: Record<string, unknown>\n relationships?: Record<string, JsonApiRelationship>\n}\n\nexport interface JsonApiMeta {\n // Pagination\n totalPages?: number\n totalItems?: number\n currentPage?: number\n itemsPerPage?: number\n\n // Common metadata\n timestamp?: string | number\n version?: string\n copyright?: string\n\n // Allow additional custom properties\n [key: string]: unknown\n}\n\nexport interface JsonApiLinkObject {\n href: string\n rel?: string\n describedby?: JsonApiLink\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: JsonApiMeta\n}\n\nexport type JsonApiLink = null | string | JsonApiLinkObject\n\nexport interface JsonApiLinks {\n self?: JsonApiLink\n related?: JsonApiLink\n describedby?: JsonApiLink\n first?: JsonApiLink\n last?: JsonApiLink\n prev?: JsonApiLink\n next?: JsonApiLink\n}\n\nexport interface JsonApiDocument {\n links?: JsonApiLinks\n data?: JsonApiResource | JsonApiResource[]\n errors?: JsonApiError[]\n included?: JsonApiResource[]\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiReference extends JsonApiResourceIdentifier {\n relationship?: string\n}\n\nexport interface JsonApiError {\n id: string\n status: string\n code?: string\n title: string\n detail?: string\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicOperation {\n op: 'add' | 'update' | 'remove'\n data?: JsonApiResource\n ref?: JsonApiReference\n}\n\nexport interface JsonApiAtomicResult {\n data: JsonApiResource\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicDocument {\n 'atomic:operations'?: JsonApiAtomicOperation[]\n 'atomic:results'?: JsonApiAtomicResult[]\n errors?: JsonApiError[]\n}\n\nexport interface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n data: BaseEntity\n}\n\nexport interface BaseEntity {\n id: string\n lid?: string\n type: string\n}\n\n/**\n * Model definition\n */\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * Optional relationships for the model\n */\n relationships?: Record<string, Relationship>\n}\n\nexport interface JsonApiConfig {\n /**\n * The URL for the JSON:API endpoint\n */\n endpoint: string\n /**\n * Model definitions for the store\n */\n modelDefinitions: ModelDefinition[]\n /**\n * Whether to convert kebab-case names from JSON:API (older convention) to camelCase\n */\n kebabCase?: boolean\n}\n\nexport enum RelationshipType {\n HasMany = 0,\n BelongsTo = 1,\n}\n\n/**\n * Relationship definition\n */\nexport interface Relationship {\n /** The JSON:API type name of the related model */\n type: string\n /** The relationship type */\n relationshipType: RelationshipType\n}\n\nfunction setRelationship(record: BaseEntity, name: string, value: unknown): void {\n ;(record as unknown as Record<string, unknown>)[name] = value\n}\n\nexport type JsonApi = ReturnType<typeof useJsonApi>\n\nfunction serializeRid(entity: BaseEntity): JsonApiResourceIdentifier {\n const rid: JsonApiResourceIdentifier = { type: entity.type }\n if (entity.lid) rid.lid = entity.lid\n else if (entity.id) rid.id = entity.id\n return rid\n}\n\nexport function useJsonApi(config: JsonApiConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n // Map type names to their definitions\n const modelDefinitions = new Map<string, ModelDefinition>()\n const relationshipDefinitions = new Map<string, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n modelDefinitions.set(modelDef.type, modelDef)\n if (modelDef.relationships) relationshipDefinitions.set(modelDef.type, modelDef.relationships)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function serialize(record: BaseEntity): JsonApiResource {\n const relationships = relationshipDefinitions.get(record.type)\n const resource: JsonApiResource = serializeRid(record) as JsonApiResource\n resource.attributes = {}\n if (relationships) resource.relationships = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === 'id' || key === 'lid' || key === 'type' || value === undefined) continue\n if (relationships && key in relationships && resource.relationships) {\n const rel = relationships[key]\n if (rel.relationshipType === RelationshipType.HasMany) {\n const entities = value as unknown as BaseEntity[]\n resource.relationships[key] = {\n data: entities.map(serializeRid),\n }\n } else if (rel.relationshipType === RelationshipType.BelongsTo) {\n const entity = value as unknown as BaseEntity\n resource.relationships[key] = {\n data: serializeRid(entity),\n }\n } else {\n throw new Error(`Unknown relationship type for ${key}`)\n }\n } else {\n resource.attributes[key] = value\n }\n }\n return resource\n }\n\n function createRecord<T extends BaseEntity>(type: string, properties: Partial<T> & { id?: string }): T {\n const modelDef = modelDefinitions.get(type)\n if (!modelDef) throw new Error(`Model type ${type} not defined`)\n\n const id = properties.id ?? crypto.randomUUID()\n\n const record = { id, type, ...properties } as T\n\n // Normalize property keys if needed\n if (config.kebabCase) {\n const normalizedRecord = { id, type } as BaseEntity & Record<string, unknown>\n for (const [key, value] of Object.entries(properties))\n if (key !== 'id' && value !== undefined) normalizedRecord[normalize(key)] = value\n return normalizedRecord as T\n }\n\n return record\n }\n\n function resourcesToRecords(resources: JsonApiResource[], included?: JsonApiResource[]): BaseEntity[] {\n function resourceToRecord(resource: JsonApiResource): BaseEntity {\n return createRecord(resource.type, {\n id: resource.id,\n ...resource.attributes,\n })\n }\n\n function setRecord(map: Map<string, Map<string, BaseEntity>>, record: BaseEntity) {\n if (!map.has(record.type)) map.set(record.type, new Map())\n map.get(record.type)?.set(record.id, record)\n }\n\n function getRecord(map: Map<string, Map<string, BaseEntity>>, rid: JsonApiResourceIdentifier) {\n if (rid.id === undefined) throw new Error('Resource identifier must have an id')\n if (!map.has(rid.type)) map.set(rid.type, new Map())\n return map.get(rid.type)?.get(rid.id)\n }\n\n const includedMap = new Map<string, Map<string, BaseEntity>>()\n if (included) for (const resource of included) setRecord(includedMap, resourceToRecord(resource))\n\n const records = resources.map(resourceToRecord)\n const recordsMap = new Map<string, Map<string, BaseEntity>>()\n for (const record of records) setRecord(recordsMap, record)\n\n function populateRelationships(resource: JsonApiResource) {\n const record = getRecord(recordsMap, resource) ?? getRecord(includedMap, resource)\n if (!record) throw new Error('Unexpected not found record')\n\n if (!resource.relationships) return\n\n const rels = relationshipDefinitions.get(resource.type)\n if (!rels) return\n\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) continue\n if (!reldoc.data) continue\n const rids =\n rel.relationshipType === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n const relatedRecords = rids\n .filter((d) => d && d.type === rel.type)\n .map((d) => getRecord(includedMap, d) || getRecord(recordsMap, d))\n .filter(Boolean)\n setRelationship(\n record,\n normalizedName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n }\n }\n\n if (included) {\n for (const r of resources) populateRelationships(r)\n for (const r of included) populateRelationships(r)\n }\n\n return records\n }\n\n async function findAll<T extends BaseEntity>(\n type: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<{ doc: JsonApiDocument; records: T[] }> {\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords(resources, doc.included) as T[]\n return { doc, records }\n }\n\n async function findRecord<T extends BaseEntity>(\n type: string,\n id: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<T> {\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords([resource], doc.included) as T[]\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record\n }\n\n async function findRelated(\n record: BaseEntity,\n relationshipName: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<JsonApiDocument> {\n const type = record.type\n const rels = relationshipDefinitions.get(type)\n if (!rels) throw new Error(`Model ${type} has no relationships`)\n\n const rel = rels[relationshipName]\n if (!rel) throw new Error(`Relationship ${relationshipName} not defined`)\n\n if (rel.relationshipType === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id, relationshipName, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = createRecord(rel.type, {\n id: related.id,\n ...related.attributes,\n })\n setRelationship(record, relationshipName, relatedRecord)\n return doc\n }\n\n const doc = await _fetcher.fetchHasMany(type, record.id, relationshipName, options, params)\n const related =\n rel.relationshipType === RelationshipType.HasMany\n ? (doc.data as JsonApiResource[])\n : [doc.data as JsonApiResource]\n\n const relatedRecords = related.map((r) =>\n createRecord(rel.type, {\n id: r.id,\n ...r.attributes,\n }),\n )\n\n setRelationship(\n record,\n relationshipName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n\n return doc\n }\n\n async function saveRecord<T extends BaseEntity>(record: BaseEntity, options?: FetchOptions): Promise<T> {\n const resource = serialize(record)\n const doc = await _fetcher.post(resource, options)\n const records = resourcesToRecords([doc.data] as JsonApiResource[])\n return records[0] as T\n }\n\n async function saveAtomic(\n operations: AtomicOperation[],\n options?: FetchOptions,\n ): Promise<{ doc: JsonApiAtomicDocument; records: BaseEntity[] } | undefined> {\n const atomicOperations = operations.map((op) => ({ op: op.op, data: serialize(op.data) }) as JsonApiAtomicOperation)\n const atomicDoc: JsonApiAtomicDocument = {\n 'atomic:operations': atomicOperations,\n }\n const doc = await _fetcher.postAtomic(atomicDoc, options)\n if (!doc) return\n const records = doc['atomic:results'] ? resourcesToRecords(doc['atomic:results'].map((r) => r.data)) : []\n return { doc, records }\n }\n\n return {\n findAll,\n findRecord,\n findRelated,\n createRecord,\n saveRecord,\n saveAtomic,\n }\n}\n"],"names":["resolvePath","segments","req","url","options","headers","searchParams","method","signal","body","textSearchParams","finalUrl","response","postAtomic","JsonApiFetcherImpl","endpoint","params","requestOptions","key","value","type","id","name","resource","newOptions","doc","camel","str","match","RelationshipType","setRelationship","record","serializeRid","entity","rid","useJsonApi","config","fetcher","_fetcher","modelDefinitions","relationshipDefinitions","modelDef","normalize","serialize","relationships","rel","entities","createRecord","properties","normalizedRecord","resourcesToRecords","resources","included","resourceToRecord","setRecord","map","getRecord","includedMap","records","recordsMap","populateRelationships","rels","reldoc","normalizedName","relatedRecords","d","r","findAll","findRecord","findRelated","relationshipName","related","relatedRecord","saveRecord","saveAtomic","operations","atomicDoc","op"],"mappings":"AAEA,SAASA,KAAeC,GAA4B;AAClD,SAAO,IAAI,IAAIA,EAAS,KAAK,GAAG,CAAC,EAAE;AACrC;AA6BA,eAAeC,EAAIC,GAAaC,GAAkB;AAChD,QAAM,EAAE,SAAAC,GAAS,cAAAC,GAAc,QAAAC,GAAQ,QAAAC,GAAQ,MAAAC,MAASL,GAClDM,IAAmBJ,IAAe,IAAIA,CAAY,KAAK,IACvDK,IAAWR,EAAI,QAAQ,qBAAqBO,CAAgB,GAC5DE,IAAW,MAAM,MAAMD,GAAU;AAAA,IACrC,QAAAJ;AAAA,IACA,SAAAF;AAAA,IACA,QAAAG;AAAA,IACA,MAAAC;AAAA,EAAA,CACD;AACD,MAAI,CAACG,EAAS,GAAI,OAAM,IAAI,MAAM,uBAAuBA,EAAS,MAAM,IAAIA,EAAS,UAAU,EAAE;AAEjG,SADc,MAAMA,EAAS,KAAA;AAE/B;AAEA,eAAeC,EAAWV,GAAaC,GAAuB;AAC5D,QAAM,EAAE,QAAAI,GAAQ,MAAAC,EAAA,IAASL,GACnBG,IAAS,QACTF,IAAU,IAAI,QAAQD,EAAQ,WAAW,CAAA,CAAE;AACjD,EAAAC,EAAQ,OAAO,UAAU,gEAAgE,GACzFA,EAAQ,OAAO,gBAAgB,gEAAgE;AAC/F,QAAMO,IAAW,MAAM,MAAMT,GAAK;AAAA,IAChC,QAAAI;AAAA,IACA,SAAAF;AAAA,IACA,QAAAG;AAAA,IACA,MAAAC;AAAA,EAAA,CACD;AACD,MAAI,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BpD,IAAM,MAAMa,EAAS,WAAWsC,GAAWxE,CAAO;AACxD,QAAI,CAACqB,EAAK;AACV,UAAMiC,IAAUjC,EAAI,gBAAgB,IAAIyB,EAAmBzB,EAAI,gBAAgB,EAAE,IAAI,CAACyC,MAAMA,EAAE,IAAI,CAAC,IAAI,CAAA;AACvG,WAAO,EAAE,KAAAzC,GAAK,SAAAiC,EAAA;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,SAAAS;AAAA,IACA,YAAAC;AAAA,IACA,aAAAC;AAAA,IACA,cAAAtB;AAAA,IACA,YAAA0B;AAAA,IACA,YAAAC;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api.ts"],"sourcesContent":["import type { JsonApiAtomicDocument, JsonApiDocument, JsonApiResource } from './json-api.ts'\n\nfunction resolvePath(...segments: string[]): string {\n return new URL(segments.join('/')).href\n}\n\nexport interface PageOption {\n size?: number\n number?: number\n}\n\nexport interface FetchOptions {\n fields?: Record<string, string[]>\n page?: PageOption\n include?: string[]\n filter?: string\n headers?: HeadersInit\n body?: BodyInit\n signal?: AbortSignal\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface Options {\n searchParams?: URLSearchParams\n headers: Headers\n method?: string\n body?: BodyInit\n signal?: AbortSignal\n}\n\nclass HttpError extends Error {\n constructor(\n message: string,\n public status: number,\n public document?: JsonApiDocument,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n\nasync function tryError(response: Response) {\n if (response.ok) return\n let errorMessage = `HTTP error! status: ${response.status} ${response.statusText}`\n let errorDocument: JsonApiDocument | undefined\n try {\n errorDocument = (await response.json()) as JsonApiDocument\n if (errorDocument.errors && errorDocument.errors.length > 0) {\n const firstError = errorDocument.errors[0]\n errorMessage += ` - ${firstError.title}: ${firstError.detail ?? ''}`\n }\n } catch {\n // Ignore JSON parsing errors\n }\n throw new HttpError(errorMessage, response.status, errorDocument)\n}\n\nasync function req(url: string, options: Options) {\n const { headers, searchParams, method, signal, body } = options\n const textSearchParams = searchParams ? `?${searchParams}` : ''\n const finalUrl = url.replace(/(?:\\?.*?)?(?=#|$)/, textSearchParams)\n const response = await fetch(finalUrl, {\n method,\n headers,\n signal,\n body,\n })\n tryError(response)\n const data = (await response.json()) as JsonApiDocument\n return data\n}\n\nasync function postAtomic(url: string, options: FetchOptions) {\n const { signal, body } = options\n const method = 'POST'\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n headers.append('Content-Type', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n const response = await fetch(url, {\n method,\n headers,\n signal,\n body,\n })\n tryError(response)\n if (response.status === 204) return\n const data = (await response.json()) as JsonApiAtomicDocument\n return data\n}\n\nexport type JsonApiFetcher = InstanceType<typeof JsonApiFetcherImpl>\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(public endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, body?: BodyInit): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json')\n const requestOptions = { searchParams, headers, body }\n if (options.fields)\n for (const [key, value] of Object.entries(options.fields)) searchParams.append(`fields[${key}]`, value.join(','))\n if (options.page?.size) searchParams.append('page[size]', options.page.size.toString())\n if (options.page?.number) searchParams.append('page[number]', options.page.number.toString())\n if (options.include) searchParams.append('include', options.include.join(','))\n if (options.filter) searchParams.append('filter', options.filter)\n for (const [key, value] of Object.entries(params)) searchParams.append(key, value)\n return requestOptions\n }\n async fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams) {\n const segments = [this.endpoint, type]\n if (id) segments.push(id)\n const url = resolvePath(...segments)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await req(url, this.createOptions(options, params))\n const resources = doc.data as JsonApiResource[]\n return resources\n }\n async fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id)\n const doc = await req(url, this.createOptions(options, params))\n const resource = doc.data as JsonApiResource\n return resource\n }\n async fetchHasMany(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async fetchBelongsTo(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await req(url, this.createOptions(options, params))\n return doc\n }\n async post(resource: JsonApiResource, options?: FetchOptions) {\n const url = resolvePath(this.endpoint, resource.type)\n const postDoc: JsonApiDocument = {\n data: resource,\n }\n const body = JSON.stringify(postDoc)\n const newOptions = this.createOptions(options, {}, body)\n newOptions.method = 'POST'\n newOptions.headers.set('Content-Type', 'application/vnd.api+json')\n const doc = (await req(url, newOptions)) as JsonApiDocument\n return doc\n }\n async postAtomic(doc: JsonApiAtomicDocument, options: FetchOptions = {}) {\n const url = new URL([this.endpoint, 'operations'].join('/')).href\n options.body = JSON.stringify(doc)\n const results = await postAtomic(url, options)\n return results\n }\n}\n","/**\n * Convert str from kebab-case to camelCase\n */\nexport function camel(str: string) {\n return str.replace(/[-][a-z\\u00E0-\\u00F6\\u00F8-\\u00FE]/g, (match) => match.slice(1).toUpperCase())\n}\n","import { type FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher.ts'\nimport { camel } from './util.ts'\n\nexport interface JsonApiResourceIdentifier {\n id?: string\n lid?: string\n type: string\n}\n\nexport interface JsonApiRelationship {\n data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[]\n}\n\nexport interface JsonApiResource {\n id?: string\n lid?: string\n type: string\n attributes: Record<string, unknown>\n relationships?: Record<string, JsonApiRelationship>\n}\n\nexport interface JsonApiMeta {\n // Pagination\n totalPages?: number\n totalItems?: number\n currentPage?: number\n itemsPerPage?: number\n\n // Common metadata\n timestamp?: string | number\n version?: string\n copyright?: string\n\n // Allow additional custom properties\n [key: string]: unknown\n}\n\nexport interface JsonApiLinkObject {\n href: string\n rel?: string\n describedby?: JsonApiLink\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: JsonApiMeta\n}\n\nexport type JsonApiLink = null | string | JsonApiLinkObject\n\nexport interface JsonApiLinks {\n self?: JsonApiLink\n related?: JsonApiLink\n describedby?: JsonApiLink\n first?: JsonApiLink\n last?: JsonApiLink\n prev?: JsonApiLink\n next?: JsonApiLink\n}\n\nexport interface JsonApiDocument {\n links?: JsonApiLinks\n data?: JsonApiResource | JsonApiResource[]\n errors?: JsonApiError[]\n included?: JsonApiResource[]\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiReference extends JsonApiResourceIdentifier {\n relationship?: string\n}\n\nexport interface JsonApiError {\n id: string\n status: string\n code?: string\n title: string\n detail?: string\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicOperation {\n op: 'add' | 'update' | 'remove'\n data?: JsonApiResource | JsonApiResourceIdentifier[]\n ref?: JsonApiReference\n}\n\nexport interface JsonApiAtomicResult {\n data: JsonApiResource\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicDocument {\n 'atomic:operations'?: JsonApiAtomicOperation[]\n 'atomic:results'?: JsonApiAtomicResult[]\n errors?: JsonApiError[]\n}\n\nexport interface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n data: BaseEntity\n}\n\nexport interface BaseEntity {\n id: string\n lid?: string\n type: string\n}\n\n/**\n * Model definition\n */\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * Optional relationships for the model\n */\n relationships?: Record<string, Relationship>\n}\n\nexport interface JsonApiConfig {\n /**\n * The URL for the JSON:API endpoint\n */\n endpoint: string\n /**\n * Model definitions for the store\n */\n modelDefinitions: ModelDefinition[]\n /**\n * Whether to convert kebab-case names from JSON:API (older convention) to camelCase\n */\n kebabCase?: boolean\n}\n\nexport enum RelationshipType {\n HasMany = 0,\n BelongsTo = 1,\n}\n\n/**\n * Relationship definition\n */\nexport interface Relationship {\n /** The JSON:API type name of the related model */\n type: string\n /** The relationship type */\n relationshipType: RelationshipType\n}\n\nfunction setRelationship(record: BaseEntity, name: string, value: unknown): void {\n ;(record as unknown as Record<string, unknown>)[name] = value\n}\n\nexport type JsonApi = ReturnType<typeof useJsonApi>\n\nfunction serializeRid(entity: BaseEntity): JsonApiResourceIdentifier {\n const rid: JsonApiResourceIdentifier = { type: entity.type }\n if (entity.lid) rid.lid = entity.lid\n else if (entity.id) rid.id = entity.id\n return rid\n}\n\nexport function useJsonApi(config: JsonApiConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n // Map type names to their definitions\n const modelDefinitions = new Map<string, ModelDefinition>()\n const relationshipDefinitions = new Map<string, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n modelDefinitions.set(modelDef.type, modelDef)\n if (modelDef.relationships) relationshipDefinitions.set(modelDef.type, modelDef.relationships)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function serialize(record: BaseEntity): JsonApiResource {\n const relationships = relationshipDefinitions.get(record.type)\n const resource: JsonApiResource = serializeRid(record) as JsonApiResource\n resource.attributes = {}\n if (relationships) resource.relationships = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === 'id' || key === 'lid' || key === 'type' || value === undefined) continue\n if (relationships && key in relationships && resource.relationships) {\n const rel = relationships[key]\n if (rel.relationshipType === RelationshipType.HasMany) {\n const entities = value as unknown as BaseEntity[]\n resource.relationships[key] = {\n data: entities.map(serializeRid),\n }\n } else if (rel.relationshipType === RelationshipType.BelongsTo) {\n const entity = value as unknown as BaseEntity\n resource.relationships[key] = {\n data: serializeRid(entity),\n }\n } else {\n throw new Error(`Unknown relationship type for ${key}`)\n }\n } else {\n resource.attributes[key] = value\n }\n }\n return resource\n }\n\n function createRecord<T extends BaseEntity>(type: string, properties: Partial<T> & { id?: string }): T {\n const modelDef = modelDefinitions.get(type)\n if (!modelDef) throw new Error(`Model type ${type} not defined`)\n\n const id = properties.id ?? crypto.randomUUID()\n\n const record = { id, type, ...properties } as T\n\n // Normalize property keys if needed\n if (config.kebabCase) {\n const normalizedRecord = { id, type } as BaseEntity & Record<string, unknown>\n for (const [key, value] of Object.entries(properties))\n if (key !== 'id' && value !== undefined) normalizedRecord[normalize(key)] = value\n return normalizedRecord as T\n }\n\n return record\n }\n\n function resourcesToRecords(resources: JsonApiResource[], included?: JsonApiResource[]): BaseEntity[] {\n function resourceToRecord(resource: JsonApiResource): BaseEntity {\n return createRecord(resource.type, {\n id: resource.id,\n ...resource.attributes,\n })\n }\n\n function setRecord(map: Map<string, Map<string, BaseEntity>>, record: BaseEntity) {\n if (!map.has(record.type)) map.set(record.type, new Map())\n map.get(record.type)?.set(record.id, record)\n }\n\n function getRecord(map: Map<string, Map<string, BaseEntity>>, rid: JsonApiResourceIdentifier) {\n if (rid.id === undefined) throw new Error('Resource identifier must have an id')\n if (!map.has(rid.type)) map.set(rid.type, new Map())\n return map.get(rid.type)?.get(rid.id)\n }\n\n const includedMap = new Map<string, Map<string, BaseEntity>>()\n if (included) for (const resource of included) setRecord(includedMap, resourceToRecord(resource))\n\n const records = resources.map(resourceToRecord)\n const recordsMap = new Map<string, Map<string, BaseEntity>>()\n for (const record of records) setRecord(recordsMap, record)\n\n function populateRelationships(resource: JsonApiResource) {\n const record = getRecord(recordsMap, resource) ?? getRecord(includedMap, resource)\n if (!record) throw new Error('Unexpected not found record')\n\n if (!resource.relationships) return\n\n const rels = relationshipDefinitions.get(resource.type)\n if (!rels) return\n\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) continue\n if (!reldoc.data) continue\n const rids =\n rel.relationshipType === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n const relatedRecords = rids\n .filter((d) => d && d.type === rel.type)\n .map((d) => getRecord(includedMap, d) || getRecord(recordsMap, d))\n .filter(Boolean)\n setRelationship(\n record,\n normalizedName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n }\n }\n\n if (included) {\n for (const r of resources) populateRelationships(r)\n for (const r of included) populateRelationships(r)\n }\n\n return records\n }\n\n async function findAll<T extends BaseEntity>(\n type: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<{ doc: JsonApiDocument; records: T[] }> {\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords(resources, doc.included) as T[]\n return { doc, records }\n }\n\n async function findRecord<T extends BaseEntity>(\n type: string,\n id: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<T> {\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords([resource], doc.included) as T[]\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record\n }\n\n async function findRelated(\n record: BaseEntity,\n relationshipName: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<JsonApiDocument> {\n const type = record.type\n const rels = relationshipDefinitions.get(type)\n if (!rels) throw new Error(`Model ${type} has no relationships`)\n\n const rel = rels[relationshipName]\n if (!rel) throw new Error(`Relationship ${relationshipName} not defined`)\n\n if (rel.relationshipType === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id, relationshipName, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = createRecord(rel.type, {\n id: related.id,\n ...related.attributes,\n })\n setRelationship(record, relationshipName, relatedRecord)\n return doc\n }\n\n const doc = await _fetcher.fetchHasMany(type, record.id, relationshipName, options, params)\n const related =\n rel.relationshipType === RelationshipType.HasMany\n ? (doc.data as JsonApiResource[])\n : [doc.data as JsonApiResource]\n\n const relatedRecords = related.map((r) =>\n createRecord(rel.type, {\n id: r.id,\n ...r.attributes,\n }),\n )\n\n setRelationship(\n record,\n relationshipName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n\n return doc\n }\n\n async function saveRecord<T extends BaseEntity>(record: BaseEntity, options?: FetchOptions): Promise<T> {\n const resource = serialize(record)\n const doc = await _fetcher.post(resource, options)\n const records = resourcesToRecords([doc.data] as JsonApiResource[])\n return records[0] as T\n }\n\n async function saveAtomic(\n operations: AtomicOperation[],\n options?: FetchOptions,\n ): Promise<{ doc: JsonApiAtomicDocument; records: BaseEntity[] } | undefined> {\n const atomicOperations = operations.map((op) => ({ op: op.op, data: serialize(op.data) }) as JsonApiAtomicOperation)\n const atomicDoc: JsonApiAtomicDocument = {\n 'atomic:operations': atomicOperations,\n }\n const doc = await _fetcher.postAtomic(atomicDoc, options)\n if (!doc) return\n const records = doc['atomic:results'] ? resourcesToRecords(doc['atomic:results'].map((r) => r.data)) : []\n return { doc, records }\n }\n\n return {\n findAll,\n findRecord,\n findRelated,\n createRecord,\n saveRecord,\n saveAtomic,\n }\n}\n"],"names":["resolvePath","segments","HttpError","message","status","document","tryError","response","errorMessage","errorDocument","firstError","req","url","options","headers","searchParams","method","signal","body","textSearchParams","finalUrl","postAtomic","JsonApiFetcherImpl","endpoint","params","requestOptions","key","value","type","id","name","resource","newOptions","doc","camel","str","match","RelationshipType","setRelationship","record","serializeRid","entity","rid","useJsonApi","config","fetcher","_fetcher","modelDefinitions","relationshipDefinitions","modelDef","normalize","serialize","relationships","rel","entities","createRecord","properties","normalizedRecord","resourcesToRecords","resources","included","resourceToRecord","setRecord","map","getRecord","includedMap","records","recordsMap","populateRelationships","rels","reldoc","normalizedName","relatedRecords","d","r","findAll","findRecord","findRelated","relationshipName","related","relatedRecord","saveRecord","saveAtomic","operations","atomicDoc","op"],"mappings":"AAEA,SAASA,KAAeC,GAA4B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