@fakeware/core 0.0.5 → 0.0.7
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/config/index.d.mts +2 -52
- package/dist/config/index.mjs +2 -36
- package/dist/config-DGneBZWH.mjs +133 -0
- package/dist/config-DGneBZWH.mjs.map +1 -0
- package/dist/index-Brciwig_.d.mts +62 -0
- package/dist/index-jYm7NShY.d.mts +68 -0
- package/dist/index.d.mts +144 -0
- package/dist/index.mjs +610 -0
- package/dist/index.mjs.map +1 -0
- package/dist/shopware/index.d.mts +2 -27
- package/dist/shopware/index.mjs +2 -94
- package/dist/shopware-CIZF8Nuo.mjs +204 -0
- package/dist/shopware-CIZF8Nuo.mjs.map +1 -0
- package/package.json +15 -1
- package/dist/config/index.mjs.map +0 -1
- package/dist/shopware/index.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["refById","refsByEntity"],"sources":["../src/define/errors.ts","../src/define/is-plain-object.ts","../src/define/ids.ts","../src/define/registry.ts","../src/define/define.ts","../src/define/resolve.ts","../src/engine/errors.ts","../src/engine/build-graph.ts","../src/engine/discover.ts","../src/engine/evaluate.ts","../src/engine/manifest.ts","../src/engine/run.ts"],"sourcesContent":["export class RefError extends Error {}\n","export function isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)\n )\n}\n","import { createHash } from 'node:crypto'\nimport { isPlainObject } from './is-plain-object'\n\nconst FAKEWARE_NAMESPACE = 'b1e0a3f4-6c2d-5a8b-9e7f-0d1c2b3a4e5f'\n\nfunction uuidBytes(uuid: string): Uint8Array {\n const hex = uuid.replace(/-/g, '')\n const bytes = new Uint8Array(16)\n for (let i = 0; i < 16; i++) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n }\n return bytes\n}\n\nconst NAMESPACE_BYTES = uuidBytes(FAKEWARE_NAMESPACE)\n\nfunction uuidv5(name: string): string {\n const hash = createHash('sha1')\n hash.update(NAMESPACE_BYTES)\n hash.update(name, 'utf8')\n const digest = hash.digest()\n\n const bytes = digest.subarray(0, 16)\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x50\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80\n\n return bytes.toString('hex')\n}\n\nexport function deterministicId(entity: string, key: string): string {\n return uuidv5(`${entity}:${key}`)\n}\n\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize)\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(value).sort()) {\n sorted[k] = canonicalize(value[k])\n }\n return sorted\n }\n return value\n}\n\nexport function recordHash(payload: unknown): string {\n return createHash('sha256')\n .update(JSON.stringify(canonicalize(payload)))\n .digest('hex')\n}\n","import type { Ctx } from './ctx'\nimport { deterministicId } from './ids'\n\ntype RecordObject = Record<string, unknown>\nexport type RecordValue = RecordObject | ((ctx: Ctx) => RecordObject)\n\ninterface RawEntry {\n entity: string\n key?: string\n value: RecordValue\n}\n\nexport type DrainedEntries = { entity: string; entries: RawEntry[] }[]\n\nexport interface RefIndex {\n byEntity: Map<string, { byKey: Map<string, string>; all: string[] }>\n}\n\nlet entries: RawEntry[] = []\n\nexport function resetRegistry(): void {\n entries = []\n}\n\nfunction staticKey(value: RecordValue): string | undefined {\n if (typeof value !== 'function') {\n const k = (value as RecordObject).$key\n if (typeof k === 'string') return k\n }\n return undefined\n}\n\nexport function defineRecords(entity: string, recordOrRecords: RecordValue | RecordValue[]): void {\n const list = Array.isArray(recordOrRecords) ? recordOrRecords : [recordOrRecords]\n for (const value of list) {\n entries.push({ entity, key: staticKey(value), value })\n }\n}\n\nexport function drain(): DrainedEntries {\n const order: string[] = []\n const byEntity = new Map<string, RawEntry[]>()\n for (const e of entries) {\n let bucket = byEntity.get(e.entity)\n if (!bucket) {\n bucket = []\n byEntity.set(e.entity, bucket)\n order.push(e.entity)\n }\n bucket.push(e)\n }\n return order.map((entity) => ({ entity, entries: byEntity.get(entity) as RawEntry[] }))\n}\n\nexport function buildRefIndex(drained: DrainedEntries): {\n refIndex: RefIndex\n ids: Map<RawEntry, string>\n} {\n const refIndex: RefIndex = { byEntity: new Map() }\n const ids = new Map<RawEntry, string>()\n\n for (const { entity, entries: bucket } of drained) {\n const slot = { byKey: new Map<string, string>(), all: [] as string[] }\n refIndex.byEntity.set(entity, slot)\n bucket.forEach((entry, i) => {\n const idKey = entry.key ?? String(i)\n const id = deterministicId(entity, idKey)\n ids.set(entry, id)\n slot.all.push(id)\n if (entry.key) slot.byKey.set(entry.key, id)\n })\n }\n\n return { refIndex, ids }\n}\n\nexport type { RawEntry }\n","import type { Ctx } from './ctx'\nimport { RefError } from './errors'\nimport { defineRecords, type RecordValue, type RefIndex } from './registry'\nimport type { DefineRecord, EntityName } from './schema'\n\nexport function define<const E extends EntityName>(\n entity: E,\n records: DefineRecord<E> | readonly DefineRecord<E>[],\n): void {\n defineRecords(entity, records as RecordValue | RecordValue[])\n}\n\nexport function many<R extends Record<string, unknown>>(n: number, fn: (ctx: Ctx) => R): R {\n return Array.from({ length: n }, () => fn) as unknown as R\n}\n\nlet active: RefIndex | undefined\n\nexport function setActiveRefIndex(refIndex: RefIndex | undefined): void {\n active = refIndex\n}\n\nfunction requireActive(): RefIndex {\n if (!active) {\n throw new RefError('ref()/refs() may only be called while resolving definitions.')\n }\n return active\n}\n\nexport function ref(path: string): string {\n const slash = path.indexOf('/')\n if (slash === -1) {\n throw new RefError(`ref('${path}') must be of the form 'entity/key'.`)\n }\n const entity = path.slice(0, slash)\n const key = path.slice(slash + 1)\n const id = requireActive().byEntity.get(entity)?.byKey.get(key)\n if (!id) {\n throw new RefError(`ref('${path}') does not match any defined record.`)\n }\n return id\n}\n\nexport function refs(entity: string): string[] {\n const slot = requireActive().byEntity.get(entity)\n if (!slot) {\n throw new RefError(`refs('${entity}') does not match any defined entity.`)\n }\n return [...slot.all]\n}\n","import type { Ctx } from './ctx'\nimport { isPlainObject } from './is-plain-object'\n\nexport function resolveValue(value: unknown, ctx: Ctx): unknown {\n if (typeof value === 'function') {\n return resolveValue((value as (ctx: Ctx) => unknown)(ctx), ctx)\n }\n if (Array.isArray(value)) {\n return value.map((item) => resolveValue(item, ctx))\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {}\n for (const [key, v] of Object.entries(value)) {\n if (key === '$key') continue\n out[key] = resolveValue(v, ctx)\n }\n return out\n }\n return value\n}\n","import type { ReportStep } from './run'\n\nexport class GraphError extends Error {}\n\nexport class TransactionError extends Error {\n readonly rolledBack: ReportStep[]\n readonly failedEntity: string\n readonly unrevertableUpdates: boolean\n readonly compensationErrors: unknown[]\n\n constructor(\n message: string,\n options: {\n cause: unknown\n rolledBack: ReportStep[]\n failedEntity: string\n unrevertableUpdates?: boolean\n compensationErrors?: unknown[]\n },\n ) {\n super(message, { cause: options.cause })\n this.name = 'TransactionError'\n this.rolledBack = options.rolledBack\n this.failedEntity = options.failedEntity\n this.unrevertableUpdates = options.unrevertableUpdates ?? false\n this.compensationErrors = options.compensationErrors ?? []\n }\n}\n","import {\n buildRefIndex,\n type Ctx,\n type DrainedEntries,\n isPlainObject,\n type RefIndex,\n ref as refById,\n refs as refsByEntity,\n resolveValue,\n setActiveRefIndex,\n} from '../define'\nimport type { SinkRecord } from '../domain'\nimport { GraphError } from './errors'\n\nexport interface WritePlan {\n order: string[]\n records: Map<string, SinkRecord[]>\n}\n\nfunction ownerByIdOf(refIndex: RefIndex): Map<string, string> {\n const owner = new Map<string, string>()\n for (const [entity, slot] of refIndex.byEntity) {\n for (const id of slot.all) owner.set(id, entity)\n }\n return owner\n}\n\nfunction collectIdRefs(value: unknown, ownerById: Map<string, string>, into: Set<string>): void {\n if (typeof value === 'string') {\n const owner = ownerById.get(value)\n if (owner) into.add(owner)\n return\n }\n if (Array.isArray(value)) {\n for (const item of value) collectIdRefs(item, ownerById, into)\n return\n }\n if (isPlainObject(value)) {\n for (const v of Object.values(value)) collectIdRefs(v, ownerById, into)\n }\n}\n\nfunction topoSort(entities: string[], edges: Map<string, Set<string>>): string[] {\n const indegree = new Map<string, number>(entities.map((e) => [e, 0]))\n const dependents = new Map<string, string[]>(entities.map((e) => [e, []]))\n for (const [entity, deps] of edges) {\n for (const dep of deps) {\n indegree.set(entity, (indegree.get(entity) ?? 0) + 1)\n dependents.get(dep)?.push(entity)\n }\n }\n\n const queue = entities.filter((e) => (indegree.get(e) ?? 0) === 0)\n const ordered: string[] = []\n while (queue.length > 0) {\n const entity = queue.shift() as string\n ordered.push(entity)\n for (const dependent of dependents.get(entity) ?? []) {\n const next = (indegree.get(dependent) ?? 0) - 1\n indegree.set(dependent, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (ordered.length !== entities.length) {\n const cyclic = entities.filter((e) => !ordered.includes(e))\n throw new GraphError(`Reference cycle between entities: ${cyclic.join(', ')}.`)\n }\n return ordered\n}\n\nexport function buildWritePlan(drained: DrainedEntries): WritePlan {\n const { refIndex, ids } = buildRefIndex(drained)\n const ownerById = ownerByIdOf(refIndex)\n const entities = drained.map((d) => d.entity)\n\n const records = new Map<string, SinkRecord[]>()\n const edges = new Map<string, Set<string>>(entities.map((e) => [e, new Set<string>()]))\n\n setActiveRefIndex(refIndex)\n try {\n for (const { entity, entries } of drained) {\n const out: SinkRecord[] = []\n entries.forEach((entry, i) => {\n const ctx: Ctx = {\n index: i,\n count: entries.length,\n ref: refById,\n refs: refsByEntity,\n }\n const payload = resolveValue(entry.value, ctx) as Record<string, unknown>\n const id = ids.get(entry) as string\n\n const referenced = new Set<string>()\n collectIdRefs(payload, ownerById, referenced)\n for (const dep of referenced) {\n if (dep !== entity) edges.get(entity)?.add(dep)\n }\n\n out.push({ ...payload, id })\n })\n records.set(entity, out)\n }\n } finally {\n setActiveRefIndex(undefined)\n }\n\n return { order: topoSort(entities, edges), records }\n}\n","import { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst DATA_DIR = 'data'\n\nfunction isDataFile(name: string): boolean {\n return name.endsWith('.ts') && !name.endsWith('.test.ts') && !name.endsWith('.d.ts')\n}\n\nexport async function discoverDataFiles(projectRoot: string): Promise<string[]> {\n const root = join(projectRoot, DATA_DIR)\n let names: string[]\n try {\n names = await readdir(root, { recursive: true })\n } catch {\n return []\n }\n return names\n .filter(isDataFile)\n .sort()\n .map((name) => join(root, name))\n}\n","import { type DrainedEntries, drain, resetRegistry } from '../define'\nimport { loadModule } from '../runtime'\n\nexport async function evaluateDataFiles(files: string[]): Promise<DrainedEntries> {\n resetRegistry()\n for (const file of files) {\n await loadModule(file)\n }\n return drain()\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { ConfigError } from '../config'\n\nconst MANIFEST_DIR = '.fakeware'\nconst CURRENT_VERSION = 1 as const\n\nfunction shopKey(shopwareUrl: string): string {\n return createHash('sha256').update(shopwareUrl).digest('hex').slice(0, 16)\n}\n\nexport interface ManifestRecord {\n id: string\n hash: string\n}\n\nexport interface ManifestEntity {\n entity: string\n records: ManifestRecord[]\n}\n\nexport interface Manifest {\n version: 1\n fakewareVersion: string\n createdAt: string\n shopwareUrl: string\n entities: ManifestEntity[]\n checksum: string\n}\n\nexport function manifestPath(projectRoot: string, shopwareUrl: string): string {\n return join(projectRoot, MANIFEST_DIR, `${shopKey(shopwareUrl)}.json`)\n}\n\nfunction checksumOf(entities: ManifestEntity[]): string {\n const canonical = entities\n .map((e) => ({\n entity: e.entity,\n records: [...e.records].sort((a, b) => a.id.localeCompare(b.id)),\n }))\n .sort((a, b) => a.entity.localeCompare(b.entity))\n return createHash('sha256').update(JSON.stringify(canonical)).digest('hex')\n}\n\nexport interface BuildManifestInput {\n fakewareVersion: string\n createdAt: string\n shopwareUrl: string\n entities: ManifestEntity[]\n}\n\nexport function buildManifest(input: BuildManifestInput): Manifest {\n return {\n version: CURRENT_VERSION,\n fakewareVersion: input.fakewareVersion,\n createdAt: input.createdAt,\n shopwareUrl: input.shopwareUrl,\n entities: input.entities,\n checksum: checksumOf(input.entities),\n }\n}\n\nexport async function readManifest(\n projectRoot: string,\n shopwareUrl: string,\n): Promise<Manifest | null> {\n const path = manifestPath(projectRoot, shopwareUrl)\n let contents: string\n try {\n contents = await readFile(path, 'utf8')\n } catch {\n return null\n }\n const parsed = JSON.parse(contents) as { version?: number }\n switch (parsed.version) {\n case CURRENT_VERSION: {\n const manifest = parsed as Manifest\n if (checksumOf(manifest.entities) !== manifest.checksum) {\n throw new ConfigError(\n `Manifest at ${path} is corrupt (checksum mismatch). Re-run \\`fakeware up\\`.`,\n )\n }\n return manifest\n }\n default:\n throw new ConfigError(\n `Unsupported manifest version ${parsed.version} (this CLI understands up to ${CURRENT_VERSION}). Upgrade fakeware.`,\n )\n }\n}\n\nexport async function writeManifest(projectRoot: string, manifest: Manifest): Promise<void> {\n const path = manifestPath(projectRoot, manifest.shopwareUrl)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, `${JSON.stringify(manifest, null, 2)}\\n`)\n}\n\nexport async function removeManifest(projectRoot: string, shopwareUrl: string): Promise<void> {\n await rm(manifestPath(projectRoot, shopwareUrl), { force: true })\n}\n","import type { LoadedConfig } from '../config'\nimport { recordHash } from '../define'\nimport type { BatchProgress, ShopwareSink, SinkRecord, SyncOperation } from '../domain'\nimport { ATOMIC_REQUEST_BYTE_LIMIT, estimateSyncBytes } from '../shopware'\nimport { buildWritePlan } from './build-graph'\nimport { discoverDataFiles } from './discover'\nimport { TransactionError } from './errors'\nimport { evaluateDataFiles } from './evaluate'\nimport {\n buildManifest,\n type Manifest,\n type ManifestEntity,\n type ManifestRecord,\n readManifest,\n removeManifest,\n writeManifest,\n} from './manifest'\n\nexport interface Reporter {\n onStart?(entity: string, records?: number): void\n onBatch?(progress: BatchProgress): void\n onStep?(step: ReportStep): void\n onTransactionStart?(info: { mode: 'atomic' | 'saga' }): void\n onCommit?(info: { committed: number }): void\n onCompensate?(entity: string, count: number): void\n onCompensateFail?(entity: string): void\n onSkip?(info: { entity: string; error: unknown }): void\n onStop?(info: { failedEntity: string; error: unknown; message: string }): void\n}\n\nexport interface ReportStep {\n entity: string\n created: number\n updated: number\n unchanged: number\n deleted: number\n}\n\nexport type OnError = 'rollback' | 'continue' | 'stop'\n\nexport interface TransactionOptions {\n onError: OnError\n atomic: boolean\n}\n\nexport interface RunOptions {\n loaded: LoadedConfig\n sink: ShopwareSink\n dryRun?: boolean\n reporter?: Reporter\n fakewareVersion?: string\n now?: string\n transaction?: TransactionOptions\n}\n\nexport interface UpResult {\n steps: ReportStep[]\n manifestWritten: boolean\n mode: 'atomic' | 'saga' | 'dry-run' | 'noop'\n committed: number\n rolledBack: number\n}\n\nexport interface DownResult {\n steps: ReportStep[]\n reverted: boolean\n}\n\ninterface EntityWrite {\n entity: string\n toWrite: SinkRecord[]\n createdIds: string[]\n manifestRecords: ManifestRecord[]\n step: ReportStep\n}\n\nfunction priorHashes(manifest: Manifest | null): Map<string, Map<string, string>> {\n const map = new Map<string, Map<string, string>>()\n for (const e of manifest?.entities ?? []) {\n map.set(e.entity, new Map(e.records.map((r) => [r.id, r.hash])))\n }\n return map\n}\n\nfunction resolveTransaction(opts: RunOptions): TransactionOptions {\n return opts.transaction ?? opts.loaded.config.transaction\n}\n\nfunction diffEntity(\n entity: string,\n records: SinkRecord[],\n prior: Map<string, string>,\n): EntityWrite {\n const toWrite: SinkRecord[] = []\n const createdIds: string[] = []\n let created = 0\n let updated = 0\n let unchanged = 0\n const manifestRecords = records.map((record) => {\n const hash = recordHash(record)\n const previous = prior.get(record.id)\n if (previous === undefined) {\n created++\n createdIds.push(record.id)\n } else if (previous === hash) {\n unchanged++\n } else {\n updated++\n }\n if (previous !== hash) toWrite.push(record)\n return { id: record.id, hash }\n })\n return {\n entity,\n toWrite,\n createdIds,\n manifestRecords,\n step: { entity, created, updated, unchanged, deleted: 0 },\n }\n}\n\nfunction partialWrite(w: EntityWrite, committed: number): EntityWrite | null {\n if (committed <= 0) return null\n const createdSet = new Set(w.createdIds)\n const prefix = w.toWrite.slice(0, committed)\n const createdIds = prefix.map((r) => r.id).filter((id) => createdSet.has(id))\n const updated = prefix.length - createdIds.length\n if (createdIds.length === 0 && updated === 0) return null\n return {\n entity: w.entity,\n toWrite: [],\n createdIds,\n manifestRecords: [],\n step: { entity: w.entity, created: 0, updated, unchanged: 0, deleted: 0 },\n }\n}\n\nexport async function runUp(opts: RunOptions): Promise<UpResult> {\n const { loaded, sink, dryRun, reporter } = opts\n const tx = resolveTransaction(opts)\n const files = await discoverDataFiles(loaded.projectRoot)\n const drained = await evaluateDataFiles(files)\n const plan = buildWritePlan(drained)\n\n const prior = priorHashes(await readManifest(loaded.projectRoot, loaded.connection.url))\n\n const writes: EntityWrite[] = plan.order.map((entity) =>\n diffEntity(\n entity,\n plan.records.get(entity) ?? [],\n prior.get(entity) ?? new Map<string, string>(),\n ),\n )\n\n const steps = writes.map((w) => w.step)\n const manifestEntities: ManifestEntity[] = writes.map((w) => ({\n entity: w.entity,\n records: w.manifestRecords,\n }))\n const committed = steps.reduce((n, s) => n + s.created + s.updated, 0)\n const pending = writes.filter((w) => w.toWrite.length > 0)\n\n if (dryRun || pending.length === 0) {\n for (const w of writes) {\n reporter?.onStart?.(w.entity)\n reporter?.onStep?.(w.step)\n }\n return {\n steps,\n manifestWritten: false,\n mode: dryRun ? 'dry-run' : 'noop',\n committed: 0,\n rolledBack: 0,\n }\n }\n\n const writeManifestNow = (entities: ManifestEntity[]): Promise<void> =>\n writeManifest(\n loaded.projectRoot,\n buildManifest({\n fakewareVersion: opts.fakewareVersion ?? '0.0.0',\n createdAt: opts.now ?? new Date().toISOString(),\n shopwareUrl: loaded.connection.url,\n entities,\n }),\n )\n\n const operations: SyncOperation[] = pending.map((w) => ({\n entity: w.entity,\n action: 'upsert',\n records: w.toWrite,\n }))\n\n if (tx.atomic && estimateSyncBytes(operations) <= ATOMIC_REQUEST_BYTE_LIMIT) {\n reporter?.onTransactionStart?.({ mode: 'atomic' })\n try {\n await sink.applyAtomic(operations)\n } catch (error) {\n const message = 'Apply failed — Shopware rolled back all changes.'\n reporter?.onStop?.({ failedEntity: '', error, message })\n throw new TransactionError(message, {\n cause: error,\n rolledBack: [],\n failedEntity: '',\n })\n }\n await writeManifestNow(manifestEntities)\n reporter?.onCommit?.({ committed })\n return { steps, manifestWritten: true, mode: 'atomic', committed, rolledBack: 0 }\n }\n\n reporter?.onTransactionStart?.({ mode: 'saga' })\n const written: EntityWrite[] = []\n const skipped: { entity: string; error: unknown }[] = []\n\n for (const w of pending) {\n reporter?.onStart?.(w.entity, w.toWrite.length)\n let committedRecords = 0\n try {\n await sink.upsert(w.entity, w.toWrite, (progress) => {\n committedRecords = progress.records\n reporter?.onBatch?.(progress)\n })\n written.push(w)\n reporter?.onStep?.(w.step)\n } catch (error) {\n if (tx.onError === 'stop') {\n const message = `Writing ${w.entity} failed — stopped.`\n reporter?.onStop?.({ failedEntity: w.entity, error, message })\n throw new TransactionError(message, {\n cause: error,\n rolledBack: [],\n failedEntity: w.entity,\n })\n }\n if (tx.onError === 'continue') {\n skipped.push({ entity: w.entity, error })\n reporter?.onSkip?.({ entity: w.entity, error })\n continue\n }\n const message = `Could not apply ${w.entity}.`\n reporter?.onStop?.({ failedEntity: w.entity, error, message })\n const partial = partialWrite(w, committedRecords)\n const toCompensate = partial ? [...written, partial] : written\n const { rolledBack, unrevertableUpdates, compensationErrors } = await compensate(\n sink,\n toCompensate,\n reporter,\n )\n throw new TransactionError(message, {\n cause: error,\n rolledBack,\n failedEntity: w.entity,\n unrevertableUpdates,\n compensationErrors,\n })\n }\n }\n\n for (const w of writes) {\n if (!written.includes(w) && !skipped.some((s) => s.entity === w.entity)) {\n reporter?.onStart?.(w.entity)\n reporter?.onStep?.(w.step)\n }\n }\n\n if (skipped.length > 0) {\n const writtenEntities = new Set(written.map((w) => w.entity))\n await writeManifestNow(restrictManifest(manifestEntities, prior, writtenEntities))\n const first = skipped[0] as { entity: string; error: unknown }\n throw new TransactionError(\n `Applied with ${skipped.length} skipped entit${skipped.length === 1 ? 'y' : 'ies'}.`,\n { cause: skipped, rolledBack: [], failedEntity: first.entity },\n )\n }\n\n await writeManifestNow(manifestEntities)\n reporter?.onCommit?.({ committed })\n return { steps, manifestWritten: true, mode: 'saga', committed, rolledBack: 0 }\n}\n\nasync function compensate(\n sink: ShopwareSink,\n written: EntityWrite[],\n reporter?: Reporter,\n): Promise<{\n rolledBack: ReportStep[]\n unrevertableUpdates: boolean\n compensationErrors: unknown[]\n}> {\n const rolledBack: ReportStep[] = []\n const compensationErrors: unknown[] = []\n for (const w of [...written].reverse()) {\n if (w.createdIds.length === 0) continue\n try {\n await sink.delete(w.entity, w.createdIds)\n rolledBack.push({\n entity: w.entity,\n created: 0,\n updated: 0,\n unchanged: 0,\n deleted: w.createdIds.length,\n })\n reporter?.onCompensate?.(w.entity, w.createdIds.length)\n } catch (error) {\n compensationErrors.push(error)\n reporter?.onCompensateFail?.(w.entity)\n }\n }\n const unrevertableUpdates = written.some((w) => w.step.updated > 0)\n return { rolledBack, unrevertableUpdates, compensationErrors }\n}\n\nfunction restrictManifest(\n desired: ManifestEntity[],\n prior: Map<string, Map<string, string>>,\n writtenEntities: Set<string>,\n): ManifestEntity[] {\n const out: ManifestEntity[] = []\n const seen = new Set<string>()\n for (const e of desired) {\n seen.add(e.entity)\n if (writtenEntities.has(e.entity)) {\n out.push(e)\n } else {\n const priorRecords = prior.get(e.entity)\n if (priorRecords && priorRecords.size > 0) {\n out.push({\n entity: e.entity,\n records: [...priorRecords].map(([id, hash]) => ({ id, hash })),\n })\n }\n }\n }\n for (const [entity, records] of prior) {\n if (!seen.has(entity) && records.size > 0) {\n out.push({ entity, records: [...records].map(([id, hash]) => ({ id, hash })) })\n }\n }\n return out\n}\n\nexport async function runDown(opts: RunOptions): Promise<DownResult> {\n const { loaded, sink, dryRun, reporter } = opts\n const manifest = await readManifest(loaded.projectRoot, loaded.connection.url)\n if (!manifest) return { steps: [], reverted: false }\n\n reporter?.onTransactionStart?.({ mode: 'saga' })\n\n const steps: ReportStep[] = []\n for (const entity of [...manifest.entities].reverse()) {\n const ids = entity.records.map((r) => r.id)\n reporter?.onStart?.(entity.entity, ids.length)\n if (!dryRun && ids.length > 0) {\n await sink.delete(entity.entity, ids, (progress) => reporter?.onBatch?.(progress))\n }\n const step: ReportStep = {\n entity: entity.entity,\n created: 0,\n updated: 0,\n unchanged: 0,\n deleted: ids.length,\n }\n steps.push(step)\n reporter?.onStep?.(step)\n }\n\n if (!dryRun) await removeManifest(loaded.projectRoot, loaded.connection.url)\n return { steps, reverted: !dryRun }\n}\n"],"mappings":";;;;;;AAAA,IAAa,WAAb,cAA8B,MAAM,CAAC;;;ACArC,SAAgB,cAAc,OAAkD;CAC9E,OACE,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,iBAAiB;AAE/F;;;ACDA,MAAM,qBAAqB;AAE3B,SAAS,UAAU,MAA0B;CAC3C,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE;CACjC,MAAM,QAAQ,IAAI,WAAW,EAAE;CAC/B,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KACtB,MAAM,KAAK,OAAO,SAAS,IAAI,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE;CAE5D,OAAO;AACT;AAEA,MAAM,kBAAkB,UAAU,kBAAkB;AAEpD,SAAS,OAAO,MAAsB;CACpC,MAAM,OAAO,WAAW,MAAM;CAC9B,KAAK,OAAO,eAAe;CAC3B,KAAK,OAAO,MAAM,MAAM;CAGxB,MAAM,QAFS,KAAK,OAED,CAAC,CAAC,SAAS,GAAG,EAAE;CACnC,MAAM,KAAO,MAAM,KAAgB,KAAQ;CAC3C,MAAM,KAAO,MAAM,KAAgB,KAAQ;CAE3C,OAAO,MAAM,SAAS,KAAK;AAC7B;AAEA,SAAgB,gBAAgB,QAAg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,27 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
//#region src/shopware/types.d.ts
|
|
5
|
-
interface ShopwareConnection {
|
|
6
|
-
url: string;
|
|
7
|
-
clientId: string;
|
|
8
|
-
clientSecret: string;
|
|
9
|
-
}
|
|
10
|
-
interface ShopInfo {
|
|
11
|
-
locales: string[];
|
|
12
|
-
defaultLocale: string;
|
|
13
|
-
}
|
|
14
|
-
//#endregion
|
|
15
|
-
//#region src/shopware/client.d.ts
|
|
16
|
-
type ShopwareClient = ReturnType<typeof createAdminAPIClient<operations>>;
|
|
17
|
-
declare function createShopwareClient(connection: ShopwareConnection): ShopwareClient;
|
|
18
|
-
//#endregion
|
|
19
|
-
//#region src/shopware/errors.d.ts
|
|
20
|
-
declare class ShopwareConnectionError extends Error {}
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/shopware/operations.d.ts
|
|
23
|
-
declare function validateConnection(connection: ShopwareConnection): Promise<void>;
|
|
24
|
-
declare function fetchShopInfo(connection: ShopwareConnection): Promise<ShopInfo>;
|
|
25
|
-
//#endregion
|
|
26
|
-
export { type ShopInfo, type ShopwareClient, type ShopwareConnection, ShopwareConnectionError, createShopwareClient, fetchShopInfo, validateConnection };
|
|
27
|
-
//# sourceMappingURL=index.d.mts.map
|
|
1
|
+
import { c as fetchShopInfo, d as ShopwareConnectionError, f as ShopwareClient, h as ShopwareConnection, l as toConnectionError, m as ShopInfo, n as createSyncSink, p as createShopwareClient, r as estimateSyncBytes, t as ATOMIC_REQUEST_BYTE_LIMIT, u as validateConnection } from "../index-Brciwig_.mjs";
|
|
2
|
+
export { ATOMIC_REQUEST_BYTE_LIMIT, type ShopInfo, type ShopwareClient, type ShopwareConnection, ShopwareConnectionError, createShopwareClient, createSyncSink, estimateSyncBytes, fetchShopInfo, toConnectionError, validateConnection };
|
package/dist/shopware/index.mjs
CHANGED
|
@@ -1,94 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
function createShopwareClient(connection) {
|
|
4
|
-
return createAdminAPIClient({
|
|
5
|
-
baseURL: `${connection.url.replace(/\/$/, "")}/api`,
|
|
6
|
-
credentials: {
|
|
7
|
-
grant_type: "client_credentials",
|
|
8
|
-
client_id: connection.clientId,
|
|
9
|
-
client_secret: connection.clientSecret
|
|
10
|
-
}
|
|
11
|
-
});
|
|
12
|
-
}
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region src/shopware/errors.ts
|
|
15
|
-
var ShopwareConnectionError = class extends Error {};
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/shopware/locale.ts
|
|
18
|
-
const SYSTEM_LANGUAGE_ID = "2fbb5fe2e29a4d70aa5854ce7ce3e20b";
|
|
19
|
-
function toShopInfo(rows) {
|
|
20
|
-
const seen = /* @__PURE__ */ new Set();
|
|
21
|
-
const locales = [];
|
|
22
|
-
let systemLocale;
|
|
23
|
-
for (const row of rows) {
|
|
24
|
-
const code = row.locale?.code;
|
|
25
|
-
if (!code) continue;
|
|
26
|
-
if (row.id === SYSTEM_LANGUAGE_ID) systemLocale = code;
|
|
27
|
-
if (!seen.has(code)) {
|
|
28
|
-
seen.add(code);
|
|
29
|
-
locales.push(code);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
if (locales.length === 0) throw new ShopwareConnectionError("Shopware returned no usable locales.");
|
|
33
|
-
return {
|
|
34
|
-
locales,
|
|
35
|
-
defaultLocale: systemLocale ?? locales[0]
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
//#endregion
|
|
39
|
-
//#region src/shopware/operations.ts
|
|
40
|
-
function safeJsonParse(input) {
|
|
41
|
-
try {
|
|
42
|
-
return JSON.parse(input);
|
|
43
|
-
} catch {
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
function missingPrivileges(error) {
|
|
48
|
-
for (const e of error.details.errors) {
|
|
49
|
-
if (e.code !== "FRAMEWORK__MISSING_PRIVILEGE_ERROR" || !e.detail) continue;
|
|
50
|
-
const parsed = safeJsonParse(e.detail);
|
|
51
|
-
if (parsed?.missingPrivileges?.length) return parsed.missingPrivileges;
|
|
52
|
-
}
|
|
53
|
-
return [];
|
|
54
|
-
}
|
|
55
|
-
function toConnectionError(connection, error) {
|
|
56
|
-
if (error instanceof ApiClientError) switch (error.status) {
|
|
57
|
-
case 400:
|
|
58
|
-
case 401: return new ShopwareConnectionError("Authentication failed — check the client ID and client secret of your integration.");
|
|
59
|
-
case 403: {
|
|
60
|
-
const missing = missingPrivileges(error);
|
|
61
|
-
if (missing.length) return new ShopwareConnectionError(`The integration is missing the ${missing.join(", ")} ${missing.length === 1 ? "privilege" : "privileges"} — grant them to its role in Settings → System → Integrations.`);
|
|
62
|
-
return new ShopwareConnectionError("The integration is missing permissions — grant its role admin API access in Settings → System → Integrations.");
|
|
63
|
-
}
|
|
64
|
-
case 404: return new ShopwareConnectionError(`No Shopware admin API found at ${connection.url} — check the shop URL.`);
|
|
65
|
-
default:
|
|
66
|
-
if (error.status >= 500) return new ShopwareConnectionError(`${connection.url} is not responding (HTTP ${error.status}) — the shop may be down or in maintenance.`);
|
|
67
|
-
return new ShopwareConnectionError(`Shopware returned an unexpected response (HTTP ${error.status}) from ${connection.url}.`);
|
|
68
|
-
}
|
|
69
|
-
return new ShopwareConnectionError(`Could not reach ${connection.url} — check the URL and your network connection.`);
|
|
70
|
-
}
|
|
71
|
-
async function validateConnection(connection) {
|
|
72
|
-
const client = createShopwareClient(connection);
|
|
73
|
-
try {
|
|
74
|
-
await client.invoke("infoShopwareVersion get /_info/version");
|
|
75
|
-
} catch (error) {
|
|
76
|
-
throw toConnectionError(connection, error);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
async function fetchShopInfo(connection) {
|
|
80
|
-
const client = createShopwareClient(connection);
|
|
81
|
-
try {
|
|
82
|
-
const { data } = await client.invoke("searchLanguage post /search/language", { body: {
|
|
83
|
-
associations: { locale: {} },
|
|
84
|
-
limit: 500
|
|
85
|
-
} });
|
|
86
|
-
return toShopInfo(data.data ?? []);
|
|
87
|
-
} catch (error) {
|
|
88
|
-
throw toConnectionError(connection, error);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
//#endregion
|
|
92
|
-
export { ShopwareConnectionError, createShopwareClient, fetchShopInfo, validateConnection };
|
|
93
|
-
|
|
94
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import { a as toConnectionError, c as createShopwareClient, i as fetchShopInfo, n as createSyncSink, o as validateConnection, r as estimateSyncBytes, s as ShopwareConnectionError, t as ATOMIC_REQUEST_BYTE_LIMIT } from "../shopware-CIZF8Nuo.mjs";
|
|
2
|
+
export { ATOMIC_REQUEST_BYTE_LIMIT, ShopwareConnectionError, createShopwareClient, createSyncSink, estimateSyncBytes, fetchShopInfo, toConnectionError, validateConnection };
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ApiClientError, createAdminAPIClient } from "@shopware/api-client";
|
|
3
|
+
//#region src/shopware/client.ts
|
|
4
|
+
const REQUEST_TIMEOUT_MS = 12e4;
|
|
5
|
+
function createShopwareClient(connection) {
|
|
6
|
+
return createAdminAPIClient({
|
|
7
|
+
baseURL: `${connection.url.replace(/\/$/, "")}/api`,
|
|
8
|
+
credentials: {
|
|
9
|
+
grant_type: "client_credentials",
|
|
10
|
+
client_id: connection.clientId,
|
|
11
|
+
client_secret: connection.clientSecret
|
|
12
|
+
},
|
|
13
|
+
fetchOptions: { timeout: REQUEST_TIMEOUT_MS }
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/shopware/errors.ts
|
|
18
|
+
var ShopwareConnectionError = class extends Error {};
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/shopware/locale.ts
|
|
21
|
+
const SYSTEM_LANGUAGE_ID = "2fbb5fe2e29a4d70aa5854ce7ce3e20b";
|
|
22
|
+
const languageRowSchema = z.object({
|
|
23
|
+
id: z.string(),
|
|
24
|
+
locale: z.object({ code: z.string().optional() }).nullish()
|
|
25
|
+
});
|
|
26
|
+
function parseLanguageRows(rows) {
|
|
27
|
+
const result = z.array(languageRowSchema).safeParse(rows);
|
|
28
|
+
if (!result.success) throw new ShopwareConnectionError("Shopware returned an unexpected response shape for languages.");
|
|
29
|
+
return result.data;
|
|
30
|
+
}
|
|
31
|
+
function toShopInfo(rows) {
|
|
32
|
+
const seen = /* @__PURE__ */ new Set();
|
|
33
|
+
const locales = [];
|
|
34
|
+
let systemLocale;
|
|
35
|
+
for (const row of rows) {
|
|
36
|
+
const code = row.locale?.code;
|
|
37
|
+
if (!code) continue;
|
|
38
|
+
if (row.id === SYSTEM_LANGUAGE_ID) systemLocale = code;
|
|
39
|
+
if (!seen.has(code)) {
|
|
40
|
+
seen.add(code);
|
|
41
|
+
locales.push(code);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (locales.length === 0) throw new ShopwareConnectionError("Shopware returned no usable locales.");
|
|
45
|
+
return {
|
|
46
|
+
locales,
|
|
47
|
+
defaultLocale: systemLocale ?? locales[0]
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/shopware/operations.ts
|
|
52
|
+
function safeJsonParse(input) {
|
|
53
|
+
try {
|
|
54
|
+
return JSON.parse(input);
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function isTimeoutError(error) {
|
|
60
|
+
let current = error;
|
|
61
|
+
while (current instanceof Error) {
|
|
62
|
+
if (current.name === "TimeoutError") return true;
|
|
63
|
+
current = current.cause;
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
function missingPrivileges(error) {
|
|
68
|
+
for (const e of error.details.errors) {
|
|
69
|
+
if (e.code !== "FRAMEWORK__MISSING_PRIVILEGE_ERROR" || !e.detail) continue;
|
|
70
|
+
const parsed = safeJsonParse(e.detail);
|
|
71
|
+
if (parsed?.missingPrivileges?.length) return parsed.missingPrivileges;
|
|
72
|
+
}
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
function fieldName(pointer) {
|
|
76
|
+
if (!pointer) return null;
|
|
77
|
+
const segments = pointer.split("/").filter((s) => s !== "" && !/^\d+$/.test(s));
|
|
78
|
+
return segments.length ? segments[segments.length - 1] ?? null : null;
|
|
79
|
+
}
|
|
80
|
+
function validationMessages(error) {
|
|
81
|
+
return error.details.errors.map((e) => {
|
|
82
|
+
const field = fieldName(e.source?.pointer);
|
|
83
|
+
const detail = e.detail ?? e.title ?? "Invalid value.";
|
|
84
|
+
return field ? `${field}: ${detail}` : detail;
|
|
85
|
+
}).filter((message, index, all) => all.indexOf(message) === index);
|
|
86
|
+
}
|
|
87
|
+
function toConnectionError(connection, error) {
|
|
88
|
+
if (isTimeoutError(error)) return new ShopwareConnectionError(`${connection.url} did not respond within ${REQUEST_TIMEOUT_MS / 1e3}s, the shop may be slow or unreachable.`);
|
|
89
|
+
if (error instanceof ApiClientError) switch (error.status) {
|
|
90
|
+
case 400: {
|
|
91
|
+
const messages = validationMessages(error);
|
|
92
|
+
if (!messages.length) return new ShopwareConnectionError(`Shopware rejected the request (HTTP 400) from ${connection.url}.`);
|
|
93
|
+
const shown = messages.slice(0, 5);
|
|
94
|
+
const more = messages.length - shown.length;
|
|
95
|
+
return new ShopwareConnectionError(`Shopware rejected the data:\n${shown.map((m) => ` - ${m}`).join("\n")}${more > 0 ? `\n - …and ${more} more` : ""}`);
|
|
96
|
+
}
|
|
97
|
+
case 401: return new ShopwareConnectionError("Authentication failed — check the client ID and client secret of your integration.");
|
|
98
|
+
case 403: {
|
|
99
|
+
const missing = missingPrivileges(error);
|
|
100
|
+
if (missing.length) return new ShopwareConnectionError(`The integration is missing the ${missing.join(", ")} ${missing.length === 1 ? "privilege" : "privileges"} — grant them to its role in Settings → System → Integrations.`);
|
|
101
|
+
return new ShopwareConnectionError("The integration is missing permissions — grant its role admin API access in Settings → System → Integrations.");
|
|
102
|
+
}
|
|
103
|
+
case 404: return new ShopwareConnectionError(`No Shopware admin API found at ${connection.url} — check the shop URL.`);
|
|
104
|
+
default:
|
|
105
|
+
if (error.status >= 500) return new ShopwareConnectionError(`${connection.url} is not responding (HTTP ${error.status}) — the shop may be down or in maintenance.`);
|
|
106
|
+
return new ShopwareConnectionError(`Shopware returned an unexpected response (HTTP ${error.status}) from ${connection.url}.`);
|
|
107
|
+
}
|
|
108
|
+
return new ShopwareConnectionError(`Could not reach ${connection.url} — check the URL and your network connection.`);
|
|
109
|
+
}
|
|
110
|
+
async function validateConnection(connection) {
|
|
111
|
+
const client = createShopwareClient(connection);
|
|
112
|
+
try {
|
|
113
|
+
await client.invoke("infoShopwareVersion get /_info/version");
|
|
114
|
+
} catch (error) {
|
|
115
|
+
throw toConnectionError(connection, error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function fetchShopInfo(connection) {
|
|
119
|
+
const client = createShopwareClient(connection);
|
|
120
|
+
try {
|
|
121
|
+
const { data } = await client.invoke("searchLanguage post /search/language", { body: {
|
|
122
|
+
associations: { locale: {} },
|
|
123
|
+
limit: 500
|
|
124
|
+
} });
|
|
125
|
+
return toShopInfo(parseLanguageRows(data.data ?? []));
|
|
126
|
+
} catch (error) {
|
|
127
|
+
throw toConnectionError(connection, error);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
//#region src/shopware/sink.ts
|
|
132
|
+
const SYNC_BATCH_SIZE = 50;
|
|
133
|
+
const ATOMIC_REQUEST_BYTE_LIMIT = 5 * 1024 * 1024;
|
|
134
|
+
function toSyncBody(operations) {
|
|
135
|
+
return operations.map((op) => op.action === "upsert" ? {
|
|
136
|
+
entity: op.entity,
|
|
137
|
+
action: "upsert",
|
|
138
|
+
payload: op.records
|
|
139
|
+
} : {
|
|
140
|
+
entity: op.entity,
|
|
141
|
+
action: "delete",
|
|
142
|
+
payload: op.ids.map((id) => ({ id }))
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
function estimateSyncBytes(operations) {
|
|
146
|
+
return Buffer.byteLength(JSON.stringify(toSyncBody(operations)), "utf8");
|
|
147
|
+
}
|
|
148
|
+
function chunk(items, size) {
|
|
149
|
+
const out = [];
|
|
150
|
+
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
function createSyncSink(connection, options = {}) {
|
|
154
|
+
const client = options.client ?? createShopwareClient(connection);
|
|
155
|
+
async function sync(entity, action, payload, onBatch) {
|
|
156
|
+
const batches = chunk(payload, SYNC_BATCH_SIZE);
|
|
157
|
+
let records = 0;
|
|
158
|
+
for (const [i, batch] of batches.entries()) {
|
|
159
|
+
try {
|
|
160
|
+
await client.invoke("sync post /_action/sync", {
|
|
161
|
+
headers: { "indexing-behavior": "use-queue-indexing" },
|
|
162
|
+
body: [{
|
|
163
|
+
entity,
|
|
164
|
+
action,
|
|
165
|
+
payload: batch
|
|
166
|
+
}]
|
|
167
|
+
});
|
|
168
|
+
} catch (error) {
|
|
169
|
+
throw toConnectionError(connection, error);
|
|
170
|
+
}
|
|
171
|
+
records += batch.length;
|
|
172
|
+
onBatch?.({
|
|
173
|
+
records,
|
|
174
|
+
recordsTotal: payload.length,
|
|
175
|
+
batches: i + 1,
|
|
176
|
+
batchesTotal: batches.length
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
async upsert(entity, records, onBatch) {
|
|
182
|
+
if (records.length > 0) await sync(entity, "upsert", records, onBatch);
|
|
183
|
+
},
|
|
184
|
+
async delete(entity, ids, onBatch) {
|
|
185
|
+
if (ids.length > 0) await sync(entity, "delete", ids.map((id) => ({ id })), onBatch);
|
|
186
|
+
},
|
|
187
|
+
async applyAtomic(operations) {
|
|
188
|
+
const body = toSyncBody(operations).filter((op) => op.payload.length > 0);
|
|
189
|
+
if (body.length === 0) return;
|
|
190
|
+
try {
|
|
191
|
+
await client.invoke("sync post /_action/sync", {
|
|
192
|
+
headers: { "indexing-behavior": "use-queue-indexing" },
|
|
193
|
+
body
|
|
194
|
+
});
|
|
195
|
+
} catch (error) {
|
|
196
|
+
throw toConnectionError(connection, error);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
export { toConnectionError as a, createShopwareClient as c, fetchShopInfo as i, createSyncSink as n, validateConnection as o, estimateSyncBytes as r, ShopwareConnectionError as s, ATOMIC_REQUEST_BYTE_LIMIT as t };
|
|
203
|
+
|
|
204
|
+
//# sourceMappingURL=shopware-CIZF8Nuo.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shopware-CIZF8Nuo.mjs","names":[],"sources":["../src/shopware/client.ts","../src/shopware/errors.ts","../src/shopware/locale.ts","../src/shopware/operations.ts","../src/shopware/sink.ts"],"sourcesContent":["import { createAdminAPIClient } from '@shopware/api-client'\nimport type { operations } from '@shopware/api-client/admin-api-types'\nimport type { ShopwareConnection } from './types'\n\nexport type ShopwareClient = ReturnType<typeof createAdminAPIClient<operations>>\n\nexport const REQUEST_TIMEOUT_MS = 120_000\n\nexport function createShopwareClient(connection: ShopwareConnection): ShopwareClient {\n return createAdminAPIClient<operations>({\n baseURL: `${connection.url.replace(/\\/$/, '')}/api`,\n credentials: {\n grant_type: 'client_credentials',\n client_id: connection.clientId,\n client_secret: connection.clientSecret,\n },\n fetchOptions: {\n timeout: REQUEST_TIMEOUT_MS,\n },\n })\n}\n","export class ShopwareConnectionError extends Error {}\n","import { z } from 'zod'\nimport { ShopwareConnectionError } from './errors'\nimport type { ShopInfo } from './types'\n\nconst SYSTEM_LANGUAGE_ID = '2fbb5fe2e29a4d70aa5854ce7ce3e20b'\n\nconst languageRowSchema = z.object({\n id: z.string(),\n locale: z.object({ code: z.string().optional() }).nullish(),\n})\n\nexport type LanguageRow = z.infer<typeof languageRowSchema>\n\nexport function parseLanguageRows(rows: unknown): LanguageRow[] {\n const result = z.array(languageRowSchema).safeParse(rows)\n if (!result.success) {\n throw new ShopwareConnectionError(\n 'Shopware returned an unexpected response shape for languages.',\n )\n }\n return result.data\n}\n\nexport function toShopInfo(rows: LanguageRow[]): ShopInfo {\n const seen = new Set<string>()\n const locales: string[] = []\n let systemLocale: string | undefined\n\n for (const row of rows) {\n const code = row.locale?.code\n if (!code) continue\n if (row.id === SYSTEM_LANGUAGE_ID) systemLocale = code\n if (!seen.has(code)) {\n seen.add(code)\n locales.push(code)\n }\n }\n\n if (locales.length === 0) {\n throw new ShopwareConnectionError('Shopware returned no usable locales.')\n }\n\n return { locales, defaultLocale: systemLocale ?? (locales[0] as string) }\n}\n","import { ApiClientError, type ApiError } from '@shopware/api-client'\nimport { createShopwareClient, REQUEST_TIMEOUT_MS } from './client'\nimport { ShopwareConnectionError } from './errors'\nimport { parseLanguageRows, toShopInfo } from './locale'\nimport type { ShopInfo, ShopwareConnection } from './types'\n\nfunction safeJsonParse<T>(input: string): T | null {\n try {\n return JSON.parse(input) as T\n } catch {\n return null\n }\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n let current: unknown = error\n while (current instanceof Error) {\n if (current.name === 'TimeoutError') return true\n current = current.cause\n }\n return false\n}\n\nfunction missingPrivileges(error: ApiClientError<{ errors: ApiError[] }>): string[] {\n for (const e of error.details.errors) {\n if (e.code !== 'FRAMEWORK__MISSING_PRIVILEGE_ERROR' || !e.detail) continue\n const parsed = safeJsonParse<{ missingPrivileges?: string[] }>(e.detail)\n if (parsed?.missingPrivileges?.length) return parsed.missingPrivileges\n }\n return []\n}\n\nfunction fieldName(pointer: string | undefined): string | null {\n if (!pointer) return null\n const segments = pointer.split('/').filter((s) => s !== '' && !/^\\d+$/.test(s))\n return segments.length ? (segments[segments.length - 1] ?? null) : null\n}\n\nfunction validationMessages(error: ApiClientError<{ errors: ApiError[] }>): string[] {\n return error.details.errors\n .map((e) => {\n const field = fieldName(e.source?.pointer)\n const detail = e.detail ?? e.title ?? 'Invalid value.'\n return field ? `${field}: ${detail}` : detail\n })\n .filter((message, index, all) => all.indexOf(message) === index)\n}\n\nexport function toConnectionError(\n connection: ShopwareConnection,\n error: unknown,\n): ShopwareConnectionError {\n if (isTimeoutError(error)) {\n return new ShopwareConnectionError(\n `${connection.url} did not respond within ${REQUEST_TIMEOUT_MS / 1000}s, the shop may be slow or unreachable.`,\n )\n }\n if (error instanceof ApiClientError) {\n switch (error.status) {\n case 400: {\n const messages = validationMessages(error)\n if (!messages.length) {\n return new ShopwareConnectionError(\n `Shopware rejected the request (HTTP 400) from ${connection.url}.`,\n )\n }\n const shown = messages.slice(0, 5)\n const more = messages.length - shown.length\n const list = shown.map((m) => ` - ${m}`).join('\\n')\n const tail = more > 0 ? `\\n - …and ${more} more` : ''\n return new ShopwareConnectionError(`Shopware rejected the data:\\n${list}${tail}`)\n }\n case 401:\n return new ShopwareConnectionError(\n 'Authentication failed — check the client ID and client secret of your integration.',\n )\n case 403: {\n const missing = missingPrivileges(error)\n if (missing.length) {\n return new ShopwareConnectionError(\n `The integration is missing the ${missing.join(', ')} ${missing.length === 1 ? 'privilege' : 'privileges'} — grant them to its role in Settings → System → Integrations.`,\n )\n }\n return new ShopwareConnectionError(\n 'The integration is missing permissions — grant its role admin API access in Settings → System → Integrations.',\n )\n }\n case 404:\n return new ShopwareConnectionError(\n `No Shopware admin API found at ${connection.url} — check the shop URL.`,\n )\n default:\n if (error.status >= 500) {\n return new ShopwareConnectionError(\n `${connection.url} is not responding (HTTP ${error.status}) — the shop may be down or in maintenance.`,\n )\n }\n return new ShopwareConnectionError(\n `Shopware returned an unexpected response (HTTP ${error.status}) from ${connection.url}.`,\n )\n }\n }\n return new ShopwareConnectionError(\n `Could not reach ${connection.url} — check the URL and your network connection.`,\n )\n}\n\nexport async function validateConnection(connection: ShopwareConnection): Promise<void> {\n const client = createShopwareClient(connection)\n try {\n await client.invoke('infoShopwareVersion get /_info/version')\n } catch (error) {\n throw toConnectionError(connection, error)\n }\n}\n\nexport async function fetchShopInfo(connection: ShopwareConnection): Promise<ShopInfo> {\n const client = createShopwareClient(connection)\n try {\n const { data } = await client.invoke('searchLanguage post /search/language', {\n body: { associations: { locale: {} }, limit: 500 },\n })\n return toShopInfo(parseLanguageRows(data.data ?? []))\n } catch (error) {\n throw toConnectionError(connection, error)\n }\n}\n","import type { OnBatch, ShopwareSink, SinkRecord, SyncOperation } from '../domain'\nimport { createShopwareClient, type ShopwareClient } from './client'\nimport { toConnectionError } from './operations'\nimport type { ShopwareConnection } from './types'\n\nexport interface SyncSinkOptions {\n client?: ShopwareClient\n}\n\nconst SYNC_BATCH_SIZE = 50\n\nexport const ATOMIC_REQUEST_BYTE_LIMIT = 5 * 1024 * 1024\n\ninterface SyncBodyEntry {\n entity: string\n action: 'upsert' | 'delete'\n payload: Record<string, unknown>[]\n}\n\nfunction toSyncBody(operations: SyncOperation[]): SyncBodyEntry[] {\n return operations.map((op) =>\n op.action === 'upsert'\n ? { entity: op.entity, action: 'upsert', payload: op.records }\n : { entity: op.entity, action: 'delete', payload: op.ids.map((id) => ({ id })) },\n )\n}\n\nexport function estimateSyncBytes(operations: SyncOperation[]): number {\n return Buffer.byteLength(JSON.stringify(toSyncBody(operations)), 'utf8')\n}\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n const out: T[][] = []\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))\n return out\n}\n\nexport function createSyncSink(\n connection: ShopwareConnection,\n options: SyncSinkOptions = {},\n): ShopwareSink {\n const client = options.client ?? createShopwareClient(connection)\n\n async function sync(\n entity: string,\n action: 'upsert' | 'delete',\n payload: Record<string, unknown>[],\n onBatch?: OnBatch,\n ): Promise<void> {\n const batches = chunk(payload, SYNC_BATCH_SIZE)\n let records = 0\n for (const [i, batch] of batches.entries()) {\n try {\n await client.invoke('sync post /_action/sync', {\n headers: { 'indexing-behavior': 'use-queue-indexing' },\n body: [{ entity, action, payload: batch as never }],\n })\n } catch (error) {\n throw toConnectionError(connection, error)\n }\n records += batch.length\n onBatch?.({\n records,\n recordsTotal: payload.length,\n batches: i + 1,\n batchesTotal: batches.length,\n })\n }\n }\n\n return {\n async upsert(entity: string, records: SinkRecord[], onBatch?: OnBatch): Promise<void> {\n if (records.length > 0) await sync(entity, 'upsert', records, onBatch)\n },\n async delete(entity: string, ids: string[], onBatch?: OnBatch): Promise<void> {\n if (ids.length > 0)\n await sync(\n entity,\n 'delete',\n ids.map((id) => ({ id })),\n onBatch,\n )\n },\n async applyAtomic(operations: SyncOperation[]): Promise<void> {\n const body = toSyncBody(operations).filter((op) => op.payload.length > 0)\n if (body.length === 0) return\n try {\n await client.invoke('sync post /_action/sync', {\n headers: { 'indexing-behavior': 'use-queue-indexing' },\n body: body as never,\n })\n } catch (error) {\n throw toConnectionError(connection, error)\n }\n },\n }\n}\n"],"mappings":";;;AAMA,MAAa,qBAAqB;AAElC,SAAgB,qBAAqB,YAAgD;CACnF,OAAO,qBAAiC;EACtC,SAAS,GAAG,WAAW,IAAI,QAAQ,OAAO,EAAE,EAAE;EAC9C,aAAa;GACX,YAAY;GACZ,WAAW,WAAW;GACtB,eAAe,WAAW;EAC5B;EACA,cAAc,EACZ,SAAS,mBACX;CACF,CAAC;AACH;;;ACpBA,IAAa,0BAAb,cAA6C,MAAM,CAAC;;;ACIpD,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,EAAE,OAAO;CACjC,IAAI,EAAE,OAAO;CACb,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,QAAQ;AAC5D,CAAC;AAID,SAAgB,kBAAkB,MAA8B;CAC9D,MAAM,SAAS,EAAE,MAAM,iBAAiB,CAAC,CAAC,UAAU,IAAI;CACxD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,wBACR,+DACF;CAEF,OAAO,OAAO;AAChB;AAEA,SAAgB,WAAW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,MAAM,SAAS,eAAe;EAC9C,IAAI,UAAU;EACd,KAAK,MAAM,CAAC,GAAG,UAAU,QAAQ,QAAQ,GAAG;GAC1C,IAAI;IACF,MAAM,OAAO,OAAO,2BAA2B;KAC7C,SAAS,EAAE,qBAAqB,qBAAqB;KACrD,MAAM,CAAC;MAAE;MAAQ;MAAQ,SAAS;KAAe,CAAC;IACpD,CAAC;GACH,SAAS,OAAO;IACd,MAAM,kBAAkB,YAAY,KAAK;GAC3C;GACA,WAAW,MAAM;GACjB,UAAU;IACR;IACA,cAAc,QAAQ;IACtB,SAAS,IAAI;IACb,cAAc,QAAQ;GACxB,CAAC;EACH;CACF;CAEA,OAAO;EACL,MAAM,OAAO,QAAgB,SAAuB,SAAkC;GACpF,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,QAAQ,UAAU,SAAS,OAAO;EACvE;EACA,MAAM,OAAO,QAAgB,KAAe,SAAkC;GAC5E,IAAI,IAAI,SAAS,GACf,MAAM,KACJ,QACA,UACA,IAAI,KAAK,QAAQ,EAAE,GAAG,EAAE,GACxB,OACF;EACJ;EACA,MAAM,YAAY,YAA4C;GAC5D,MAAM,OAAO,WAAW,UAAU,CAAC,CAAC,QAAQ,OAAO,GAAG,QAAQ,SAAS,CAAC;GACxE,IAAI,KAAK,WAAW,GAAG;GACvB,IAAI;IACF,MAAM,OAAO,OAAO,2BAA2B;KAC7C,SAAS,EAAE,qBAAqB,qBAAqB;KAC/C;IACR,CAAC;GACH,SAAS,OAAO;IACd,MAAM,kBAAkB,YAAY,KAAK;GAC3C;EACF;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fakeware/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "Fakeware core library that is the base for @fakeware/cli",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
"url": "git+https://github.com/fakeware-sh/fakeware.git",
|
|
10
10
|
"directory": "packages/core"
|
|
11
11
|
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.6",
|
|
14
|
+
"bun": ">=1.3.14"
|
|
15
|
+
},
|
|
12
16
|
"publishConfig": {
|
|
13
17
|
"access": "public"
|
|
14
18
|
},
|
|
@@ -16,6 +20,11 @@
|
|
|
16
20
|
"dist"
|
|
17
21
|
],
|
|
18
22
|
"exports": {
|
|
23
|
+
"./package.json": "./package.json",
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.mts",
|
|
26
|
+
"import": "./dist/index.mjs"
|
|
27
|
+
},
|
|
19
28
|
"./config": {
|
|
20
29
|
"types": "./dist/config/index.d.mts",
|
|
21
30
|
"import": "./dist/config/index.mjs"
|
|
@@ -33,6 +42,11 @@
|
|
|
33
42
|
},
|
|
34
43
|
"dependencies": {
|
|
35
44
|
"@shopware/api-client": "1.5.0",
|
|
45
|
+
"jiti": "2.7.0",
|
|
36
46
|
"zod": "4.4.3"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/bun": "1.3.14",
|
|
50
|
+
"@types/node": "22.19.19"
|
|
37
51
|
}
|
|
38
52
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/config/define.ts","../../src/config/schema.ts"],"sourcesContent":["import type { FakewareUserConfig } from './schema'\n\nexport interface ConfigEnv {\n env: Record<string, string | undefined>\n mode: string\n}\n\nexport type FakewareConfigFn = (env: ConfigEnv) => FakewareUserConfig\n\nexport function defineConfig(config: FakewareUserConfig): FakewareUserConfig\nexport function defineConfig(config: FakewareConfigFn): FakewareConfigFn\nexport function defineConfig(\n config: FakewareUserConfig | FakewareConfigFn,\n): FakewareUserConfig | FakewareConfigFn {\n return config\n}\n","import { z } from 'zod'\n\nexport const shopwareSchema = z.object({\n url: z.string().min(1, 'shopware.url is required'),\n clientId: z.string().min(1, 'shopware.clientId is required'),\n clientSecret: z.string().min(1, 'shopware.clientSecret is required'),\n})\n\nexport const mediaSchema = z.object({\n provider: z.string(),\n perProduct: z\n .object({\n min: z.number().int().nonnegative(),\n max: z.number().int().nonnegative(),\n })\n .optional(),\n})\n\nexport const pluginRefSchema = z.union([\n z.string(),\n z.tuple([z.string(), z.record(z.string(), z.unknown())]),\n])\n\nexport const fakewareConfigSchema = z.object({\n extends: z.union([z.string(), z.array(z.string())]).optional(),\n shopware: shopwareSchema.optional(),\n locale: z.string().optional(),\n seed: z.string().optional(),\n batchSize: z.number().int().positive().default(100),\n generators: z.record(z.string(), z.unknown()).default({}),\n media: mediaSchema.optional(),\n scenario: z.string().optional(),\n scenarios: z.record(z.string(), z.unknown()).default({}),\n plugins: z.array(pluginRefSchema).default([]),\n})\n\nexport type FakewareConfig = z.output<typeof fakewareConfigSchema>\n\nexport type FakewareUserConfig = z.input<typeof fakewareConfigSchema>\n"],"mappings":";;AAWA,SAAgB,aACd,QACuC;CACvC,OAAO;AACT;;;ACbA,MAAa,iBAAiB,EAAE,OAAO;CACrC,KAAK,EAAE,OAAO,EAAE,IAAI,GAAG,0BAA0B;CACjD,UAAU,EAAE,OAAO,EAAE,IAAI,GAAG,+BAA+B;CAC3D,cAAc,EAAE,OAAO,EAAE,IAAI,GAAG,mCAAmC;AACrE,CAAC;AAED,MAAa,cAAc,EAAE,OAAO;CAClC,UAAU,EAAE,OAAO;CACnB,YAAY,EACT,OAAO;EACN,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;EAClC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;CACpC,CAAC,EACA,SAAS;AACd,CAAC;AAED,MAAa,kBAAkB,EAAE,MAAM,CACrC,EAAE,OAAO,GACT,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CACzD,CAAC;AAED,MAAa,uBAAuB,EAAE,OAAO;CAC3C,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS;CAC7D,UAAU,eAAe,SAAS;CAClC,QAAQ,EAAE,OAAO,EAAE,SAAS;CAC5B,MAAM,EAAE,OAAO,EAAE,SAAS;CAC1B,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,GAAG;CAClD,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;CACxD,OAAO,YAAY,SAAS;CAC5B,UAAU,EAAE,OAAO,EAAE,SAAS;CAC9B,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;CACvD,SAAS,EAAE,MAAM,eAAe,EAAE,QAAQ,CAAC,CAAC;AAC9C,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/shopware/client.ts","../../src/shopware/errors.ts","../../src/shopware/locale.ts","../../src/shopware/operations.ts"],"sourcesContent":["import { createAdminAPIClient } from '@shopware/api-client'\nimport type { operations } from '@shopware/api-client/admin-api-types'\nimport type { ShopwareConnection } from './types'\n\nexport type ShopwareClient = ReturnType<typeof createAdminAPIClient<operations>>\n\nexport function createShopwareClient(connection: ShopwareConnection): ShopwareClient {\n return createAdminAPIClient<operations>({\n baseURL: `${connection.url.replace(/\\/$/, '')}/api`,\n credentials: {\n grant_type: 'client_credentials',\n client_id: connection.clientId,\n client_secret: connection.clientSecret,\n },\n })\n}\n","export class ShopwareConnectionError extends Error {}\n","import { ShopwareConnectionError } from './errors'\nimport type { ShopInfo } from './types'\n\nconst SYSTEM_LANGUAGE_ID = '2fbb5fe2e29a4d70aa5854ce7ce3e20b'\n\nexport interface LanguageRow {\n id: string\n locale?: { code?: string } | null\n}\n\nexport function toShopInfo(rows: LanguageRow[]): ShopInfo {\n const seen = new Set<string>()\n const locales: string[] = []\n let systemLocale: string | undefined\n\n for (const row of rows) {\n const code = row.locale?.code\n if (!code) continue\n if (row.id === SYSTEM_LANGUAGE_ID) systemLocale = code\n if (!seen.has(code)) {\n seen.add(code)\n locales.push(code)\n }\n }\n\n if (locales.length === 0) {\n throw new ShopwareConnectionError('Shopware returned no usable locales.')\n }\n\n return { locales, defaultLocale: systemLocale ?? (locales[0] as string) }\n}\n","import { ApiClientError, type ApiError } from '@shopware/api-client'\nimport { createShopwareClient } from './client'\nimport { ShopwareConnectionError } from './errors'\nimport { type LanguageRow, toShopInfo } from './locale'\nimport type { ShopInfo, ShopwareConnection } from './types'\n\nfunction safeJsonParse<T>(input: string): T | null {\n try {\n return JSON.parse(input) as T\n } catch {\n return null\n }\n}\n\nfunction missingPrivileges(error: ApiClientError<{ errors: ApiError[] }>): string[] {\n for (const e of error.details.errors) {\n if (e.code !== 'FRAMEWORK__MISSING_PRIVILEGE_ERROR' || !e.detail) continue\n const parsed = safeJsonParse<{ missingPrivileges?: string[] }>(e.detail)\n if (parsed?.missingPrivileges?.length) return parsed.missingPrivileges\n }\n return []\n}\n\nfunction toConnectionError(\n connection: ShopwareConnection,\n error: unknown,\n): ShopwareConnectionError {\n if (error instanceof ApiClientError) {\n switch (error.status) {\n case 400:\n case 401:\n return new ShopwareConnectionError(\n 'Authentication failed — check the client ID and client secret of your integration.',\n )\n case 403: {\n const missing = missingPrivileges(error)\n if (missing.length) {\n return new ShopwareConnectionError(\n `The integration is missing the ${missing.join(', ')} ${missing.length === 1 ? 'privilege' : 'privileges'} — grant them to its role in Settings → System → Integrations.`,\n )\n }\n return new ShopwareConnectionError(\n 'The integration is missing permissions — grant its role admin API access in Settings → System → Integrations.',\n )\n }\n case 404:\n return new ShopwareConnectionError(\n `No Shopware admin API found at ${connection.url} — check the shop URL.`,\n )\n default:\n if (error.status >= 500) {\n return new ShopwareConnectionError(\n `${connection.url} is not responding (HTTP ${error.status}) — the shop may be down or in maintenance.`,\n )\n }\n return new ShopwareConnectionError(\n `Shopware returned an unexpected response (HTTP ${error.status}) from ${connection.url}.`,\n )\n }\n }\n return new ShopwareConnectionError(\n `Could not reach ${connection.url} — check the URL and your network connection.`,\n )\n}\n\nexport async function validateConnection(connection: ShopwareConnection): Promise<void> {\n const client = createShopwareClient(connection)\n try {\n await client.invoke('infoShopwareVersion get /_info/version')\n } catch (error) {\n throw toConnectionError(connection, error)\n }\n}\n\nexport async function fetchShopInfo(connection: ShopwareConnection): Promise<ShopInfo> {\n const client = createShopwareClient(connection)\n try {\n const { data } = await client.invoke('searchLanguage post /search/language', {\n body: { associations: { locale: {} }, limit: 500 },\n })\n return toShopInfo((data.data ?? []) as LanguageRow[])\n } catch (error) {\n throw toConnectionError(connection, error)\n }\n}\n"],"mappings":";;AAMA,SAAgB,qBAAqB,YAAgD;CACnF,OAAO,qBAAiC;EACtC,SAAS,GAAG,WAAW,IAAI,QAAQ,OAAO,EAAE,EAAE;EAC9C,aAAa;GACX,YAAY;GACZ,WAAW,WAAW;GACtB,eAAe,WAAW;EAC5B;CACF,CAAC;AACH;;;ACfA,IAAa,0BAAb,cAA6C,MAAM,CAAC;;;ACGpD,MAAM,qBAAqB;AAO3B,SAAgB,WAAW,MAA+B;CACxD,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,UAAoB,CAAC;CAC3B,IAAI;CAEJ,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,OAAO,IAAI,QAAQ;EACzB,IAAI,CAAC,MAAM;EACX,IAAI,IAAI,OAAO,oBAAoB,eAAe;EAClD,IAAI,CAAC,KAAK,IAAI,IAAI,GAAG;GACnB,KAAK,IAAI,IAAI;GACb,QAAQ,KAAK,IAAI;EACnB;CACF;CAEA,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,wBAAwB,sCAAsC;CAG1E,OAAO;EAAE;EAAS,eAAe,gBAAiB,QAAQ;CAAc;AAC1E;;;ACxBA,S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