@fakeware/core 0.0.5 → 0.0.6
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-CSPA4Itj.mjs +130 -0
- package/dist/config-CSPA4Itj.mjs.map +1 -0
- package/dist/index-BZFBgKu8.d.mts +43 -0
- package/dist/index-Dpb1t7ns.d.mts +51 -0
- package/dist/index.d.mts +104 -0
- package/dist/index.mjs +395 -0
- package/dist/index.mjs.map +1 -0
- package/dist/shopware/index.d.mts +2 -27
- package/dist/shopware/index.mjs +68 -4
- package/dist/shopware/index.mjs.map +1 -1
- package/package.json +13 -1
- package/dist/config/index.mjs.map +0 -1
package/dist/config/index.d.mts
CHANGED
|
@@ -1,52 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
//#region src/config/schema.d.ts
|
|
4
|
-
declare const shopwareSchema: z.ZodObject<{
|
|
5
|
-
url: z.ZodString;
|
|
6
|
-
clientId: z.ZodString;
|
|
7
|
-
clientSecret: z.ZodString;
|
|
8
|
-
}, z.core.$strip>;
|
|
9
|
-
declare const mediaSchema: z.ZodObject<{
|
|
10
|
-
provider: z.ZodString;
|
|
11
|
-
perProduct: z.ZodOptional<z.ZodObject<{
|
|
12
|
-
min: z.ZodNumber;
|
|
13
|
-
max: z.ZodNumber;
|
|
14
|
-
}, z.core.$strip>>;
|
|
15
|
-
}, z.core.$strip>;
|
|
16
|
-
declare const pluginRefSchema: z.ZodUnion<readonly [z.ZodString, z.ZodTuple<[z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>], null>]>;
|
|
17
|
-
declare const fakewareConfigSchema: z.ZodObject<{
|
|
18
|
-
extends: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>;
|
|
19
|
-
shopware: z.ZodOptional<z.ZodObject<{
|
|
20
|
-
url: z.ZodString;
|
|
21
|
-
clientId: z.ZodString;
|
|
22
|
-
clientSecret: z.ZodString;
|
|
23
|
-
}, z.core.$strip>>;
|
|
24
|
-
locale: z.ZodOptional<z.ZodString>;
|
|
25
|
-
seed: z.ZodOptional<z.ZodString>;
|
|
26
|
-
batchSize: z.ZodDefault<z.ZodNumber>;
|
|
27
|
-
generators: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
28
|
-
media: z.ZodOptional<z.ZodObject<{
|
|
29
|
-
provider: z.ZodString;
|
|
30
|
-
perProduct: z.ZodOptional<z.ZodObject<{
|
|
31
|
-
min: z.ZodNumber;
|
|
32
|
-
max: z.ZodNumber;
|
|
33
|
-
}, z.core.$strip>>;
|
|
34
|
-
}, z.core.$strip>>;
|
|
35
|
-
scenario: z.ZodOptional<z.ZodString>;
|
|
36
|
-
scenarios: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
37
|
-
plugins: z.ZodDefault<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodTuple<[z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>], null>]>>>;
|
|
38
|
-
}, z.core.$strip>;
|
|
39
|
-
type FakewareConfig = z.output<typeof fakewareConfigSchema>;
|
|
40
|
-
type FakewareUserConfig = z.input<typeof fakewareConfigSchema>;
|
|
41
|
-
//#endregion
|
|
42
|
-
//#region src/config/define.d.ts
|
|
43
|
-
interface ConfigEnv {
|
|
44
|
-
env: Record<string, string | undefined>;
|
|
45
|
-
mode: string;
|
|
46
|
-
}
|
|
47
|
-
type FakewareConfigFn = (env: ConfigEnv) => FakewareUserConfig;
|
|
48
|
-
declare function defineConfig(config: FakewareUserConfig): FakewareUserConfig;
|
|
49
|
-
declare function defineConfig(config: FakewareConfigFn): FakewareConfigFn;
|
|
50
|
-
//#endregion
|
|
51
|
-
export { type ConfigEnv, type FakewareConfig, type FakewareConfigFn, type FakewareUserConfig, defineConfig, fakewareConfigSchema, mediaSchema, pluginRefSchema, shopwareSchema };
|
|
52
|
-
//# sourceMappingURL=index.d.mts.map
|
|
1
|
+
import { a as interpolate, c as FakewareConfigFn, d as FakewareUserConfig, f as fakewareConfigSchema, i as loadConfig, l as defineConfig, n as LoadConfigOptions, o as ConfigError, p as shopwareSchema, r as LoadedConfig, s as ConfigEnv, t as DEFAULT_CONFIG_FILENAME, u as FakewareConfig } from "../index-Dpb1t7ns.mjs";
|
|
2
|
+
export { type ConfigEnv, ConfigError, DEFAULT_CONFIG_FILENAME, type FakewareConfig, type FakewareConfigFn, type FakewareUserConfig, type LoadConfigOptions, type LoadedConfig, defineConfig, fakewareConfigSchema, interpolate, loadConfig, shopwareSchema };
|
package/dist/config/index.mjs
CHANGED
|
@@ -1,36 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
function defineConfig(config) {
|
|
4
|
-
return config;
|
|
5
|
-
}
|
|
6
|
-
//#endregion
|
|
7
|
-
//#region src/config/schema.ts
|
|
8
|
-
const shopwareSchema = z.object({
|
|
9
|
-
url: z.string().min(1, "shopware.url is required"),
|
|
10
|
-
clientId: z.string().min(1, "shopware.clientId is required"),
|
|
11
|
-
clientSecret: z.string().min(1, "shopware.clientSecret is required")
|
|
12
|
-
});
|
|
13
|
-
const mediaSchema = z.object({
|
|
14
|
-
provider: z.string(),
|
|
15
|
-
perProduct: z.object({
|
|
16
|
-
min: z.number().int().nonnegative(),
|
|
17
|
-
max: z.number().int().nonnegative()
|
|
18
|
-
}).optional()
|
|
19
|
-
});
|
|
20
|
-
const pluginRefSchema = z.union([z.string(), z.tuple([z.string(), z.record(z.string(), z.unknown())])]);
|
|
21
|
-
const fakewareConfigSchema = z.object({
|
|
22
|
-
extends: z.union([z.string(), z.array(z.string())]).optional(),
|
|
23
|
-
shopware: shopwareSchema.optional(),
|
|
24
|
-
locale: z.string().optional(),
|
|
25
|
-
seed: z.string().optional(),
|
|
26
|
-
batchSize: z.number().int().positive().default(100),
|
|
27
|
-
generators: z.record(z.string(), z.unknown()).default({}),
|
|
28
|
-
media: mediaSchema.optional(),
|
|
29
|
-
scenario: z.string().optional(),
|
|
30
|
-
scenarios: z.record(z.string(), z.unknown()).default({}),
|
|
31
|
-
plugins: z.array(pluginRefSchema).default([])
|
|
32
|
-
});
|
|
33
|
-
//#endregion
|
|
34
|
-
export { defineConfig, fakewareConfigSchema, mediaSchema, pluginRefSchema, shopwareSchema };
|
|
35
|
-
|
|
36
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import { a as interpolate, i as shopwareSchema, n as loadConfig, o as ConfigError, r as fakewareConfigSchema, s as defineConfig, t as DEFAULT_CONFIG_FILENAME } from "../config-CSPA4Itj.mjs";
|
|
2
|
+
export { ConfigError, DEFAULT_CONFIG_FILENAME, defineConfig, fakewareConfigSchema, interpolate, loadConfig, shopwareSchema };
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { access, readFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
//#region src/runtime/load-module.ts
|
|
6
|
+
const RUNTIME_TS_HELP = "fakeware needs to import your TypeScript files at runtime. Run it under Bun, or with Node >=22.6 (native type stripping), or via a TypeScript loader such as tsx.";
|
|
7
|
+
var LoadModuleError = class extends Error {};
|
|
8
|
+
function isBun() {
|
|
9
|
+
return typeof globalThis.Bun !== "undefined";
|
|
10
|
+
}
|
|
11
|
+
function nodeStripsTypes() {
|
|
12
|
+
const feature = process.features.typescript;
|
|
13
|
+
return feature === "strip" || feature === "transform";
|
|
14
|
+
}
|
|
15
|
+
async function loadModule(absPath) {
|
|
16
|
+
if (!isBun() && !nodeStripsTypes()) throw new LoadModuleError(RUNTIME_TS_HELP);
|
|
17
|
+
try {
|
|
18
|
+
return await import(pathToFileURL(absPath).href);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
throw new LoadModuleError(`Could not load ${absPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/config/define.ts
|
|
25
|
+
function defineConfig(config) {
|
|
26
|
+
return config;
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/config/errors.ts
|
|
30
|
+
var ConfigError = class extends Error {};
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/config/interpolate.ts
|
|
33
|
+
const ENV_REF = /^\$([A-Z0-9_]+)$/;
|
|
34
|
+
function interpolate(value, env) {
|
|
35
|
+
if (typeof value === "string") {
|
|
36
|
+
const match = ENV_REF.exec(value);
|
|
37
|
+
if (!match) return value;
|
|
38
|
+
const name = match[1];
|
|
39
|
+
const resolved = env[name];
|
|
40
|
+
if (resolved === void 0) throw new ConfigError(`Config references $${name}, but it is not set (check your .env).`);
|
|
41
|
+
return resolved;
|
|
42
|
+
}
|
|
43
|
+
if (Array.isArray(value)) return value.map((item) => interpolate(item, env));
|
|
44
|
+
if (value && typeof value === "object") {
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const [k, v] of Object.entries(value)) out[k] = interpolate(v, env);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/config/schema.ts
|
|
53
|
+
const shopwareSchema = z.object({
|
|
54
|
+
url: z.string().min(1, "shopware.url is required"),
|
|
55
|
+
clientId: z.string().min(1, "shopware.clientId is required"),
|
|
56
|
+
clientSecret: z.string().min(1, "shopware.clientSecret is required")
|
|
57
|
+
});
|
|
58
|
+
const fakewareConfigSchema = z.object({ shopware: shopwareSchema.optional() });
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/config/load.ts
|
|
61
|
+
const DEFAULT_CONFIG_FILENAME = "fakeware.config.ts";
|
|
62
|
+
async function fileExists(path) {
|
|
63
|
+
try {
|
|
64
|
+
await access(path);
|
|
65
|
+
return true;
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async function findConfig(cwd) {
|
|
71
|
+
let dir = cwd;
|
|
72
|
+
for (;;) {
|
|
73
|
+
const candidate = join(dir, DEFAULT_CONFIG_FILENAME);
|
|
74
|
+
if (await fileExists(candidate)) return candidate;
|
|
75
|
+
const parent = dirname(dir);
|
|
76
|
+
if (parent === dir) break;
|
|
77
|
+
dir = parent;
|
|
78
|
+
}
|
|
79
|
+
throw new ConfigError(`No ${DEFAULT_CONFIG_FILENAME} found in ${cwd} or any parent directory. Run \`fakeware init\` first.`);
|
|
80
|
+
}
|
|
81
|
+
async function readEnvFile(projectRoot) {
|
|
82
|
+
const path = join(projectRoot, ".env");
|
|
83
|
+
if (!await fileExists(path)) return {};
|
|
84
|
+
const out = {};
|
|
85
|
+
const contents = await readFile(path, "utf8");
|
|
86
|
+
for (const raw of contents.split("\n")) {
|
|
87
|
+
const line = raw.trim();
|
|
88
|
+
if (!line || line.startsWith("#")) continue;
|
|
89
|
+
const eq = line.indexOf("=");
|
|
90
|
+
if (eq === -1) continue;
|
|
91
|
+
const key = line.slice(0, eq).trim();
|
|
92
|
+
let val = line.slice(eq + 1).trim();
|
|
93
|
+
if (val.startsWith("\"") && val.endsWith("\"") || val.startsWith("'") && val.endsWith("'")) val = val.slice(1, -1);
|
|
94
|
+
out[key] = val;
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
function isConfigFn(value) {
|
|
99
|
+
return typeof value === "function";
|
|
100
|
+
}
|
|
101
|
+
async function loadConfig(opts = {}) {
|
|
102
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
103
|
+
const configPath = opts.configFile ? isAbsolute(opts.configFile) ? opts.configFile : resolve(cwd, opts.configFile) : await findConfig(cwd);
|
|
104
|
+
const projectRoot = dirname(configPath);
|
|
105
|
+
const env = {
|
|
106
|
+
...process.env,
|
|
107
|
+
...await readEnvFile(projectRoot)
|
|
108
|
+
};
|
|
109
|
+
const exported = (await loadModule(configPath)).default;
|
|
110
|
+
if (exported === void 0) throw new ConfigError(`${configPath} must \`export default defineConfig(...)\`.`);
|
|
111
|
+
const configEnv = {
|
|
112
|
+
env,
|
|
113
|
+
mode: opts.mode ?? "development"
|
|
114
|
+
};
|
|
115
|
+
const interpolated = interpolate(isConfigFn(exported) ? exported(configEnv) : exported, env);
|
|
116
|
+
const parsed = fakewareConfigSchema.safeParse(interpolated);
|
|
117
|
+
if (!parsed.success) throw new ConfigError(`Invalid config in ${configPath}: ${parsed.error.message}`);
|
|
118
|
+
const { shopware } = parsed.data;
|
|
119
|
+
if (!shopware) throw new ConfigError(`No \`shopware\` connection configured in ${configPath}. up/down need a shop to talk to.`);
|
|
120
|
+
return {
|
|
121
|
+
config: parsed.data,
|
|
122
|
+
connection: shopware,
|
|
123
|
+
configPath,
|
|
124
|
+
projectRoot
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
export { interpolate as a, LoadModuleError as c, shopwareSchema as i, loadModule as l, loadConfig as n, ConfigError as o, fakewareConfigSchema as r, defineConfig as s, DEFAULT_CONFIG_FILENAME as t };
|
|
129
|
+
|
|
130
|
+
//# sourceMappingURL=config-CSPA4Itj.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-CSPA4Itj.mjs","names":[],"sources":["../src/runtime/load-module.ts","../src/config/define.ts","../src/config/errors.ts","../src/config/interpolate.ts","../src/config/schema.ts","../src/config/load.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url'\n\nconst RUNTIME_TS_HELP =\n 'fakeware needs to import your TypeScript files at runtime. Run it under Bun, or with Node >=22.6 (native type stripping), or via a TypeScript loader such as tsx.'\n\nexport class LoadModuleError extends Error {}\n\nfunction isBun(): boolean {\n return typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n}\n\nfunction nodeStripsTypes(): boolean {\n const feature = (process.features as { typescript?: unknown }).typescript\n return feature === 'strip' || feature === 'transform'\n}\n\nexport async function loadModule<T = unknown>(absPath: string): Promise<T> {\n if (!isBun() && !nodeStripsTypes()) {\n throw new LoadModuleError(RUNTIME_TS_HELP)\n }\n try {\n return (await import(pathToFileURL(absPath).href)) as T\n } catch (error) {\n throw new LoadModuleError(\n `Could not load ${absPath}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n","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","export class ConfigError extends Error {}\n","import { ConfigError } from './errors'\n\nconst ENV_REF = /^\\$([A-Z0-9_]+)$/\n\nexport function interpolate<T>(value: T, env: Record<string, string | undefined>): T {\n if (typeof value === 'string') {\n const match = ENV_REF.exec(value)\n if (!match) return value\n const name = match[1] as string\n const resolved = env[name]\n if (resolved === undefined) {\n throw new ConfigError(`Config references $${name}, but it is not set (check your .env).`)\n }\n return resolved as unknown as T\n }\n if (Array.isArray(value)) {\n return value.map((item) => interpolate(item, env)) as unknown as T\n }\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n out[k] = interpolate(v, env)\n }\n return out as T\n }\n return value\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 fakewareConfigSchema = z.object({\n shopware: shopwareSchema.optional(),\n})\n\nexport type FakewareConfig = z.output<typeof fakewareConfigSchema>\n\nexport type FakewareUserConfig = z.input<typeof fakewareConfigSchema>\n","import { access, readFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { loadModule } from '../runtime'\nimport type { ShopwareConnection } from '../shopware'\nimport type { ConfigEnv, FakewareConfigFn } from './define'\nimport { ConfigError } from './errors'\nimport { interpolate } from './interpolate'\nimport { type FakewareConfig, type FakewareUserConfig, fakewareConfigSchema } from './schema'\n\nexport const DEFAULT_CONFIG_FILENAME = 'fakeware.config.ts'\n\nexport interface LoadConfigOptions {\n cwd?: string\n configFile?: string\n mode?: string\n}\n\nexport interface LoadedConfig {\n config: FakewareConfig\n connection: ShopwareConnection\n configPath: string\n projectRoot: string\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n await access(path)\n return true\n } catch {\n return false\n }\n}\n\nasync function findConfig(cwd: string): Promise<string> {\n let dir = cwd\n for (;;) {\n const candidate = join(dir, DEFAULT_CONFIG_FILENAME)\n if (await fileExists(candidate)) return candidate\n const parent = dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n throw new ConfigError(\n `No ${DEFAULT_CONFIG_FILENAME} found in ${cwd} or any parent directory. Run \\`fakeware init\\` first.`,\n )\n}\n\nasync function readEnvFile(projectRoot: string): Promise<Record<string, string>> {\n const path = join(projectRoot, '.env')\n if (!(await fileExists(path))) return {}\n const out: Record<string, string> = {}\n const contents = await readFile(path, 'utf8')\n for (const raw of contents.split('\\n')) {\n const line = raw.trim()\n if (!line || line.startsWith('#')) continue\n const eq = line.indexOf('=')\n if (eq === -1) continue\n const key = line.slice(0, eq).trim()\n let val = line.slice(eq + 1).trim()\n if ((val.startsWith('\"') && val.endsWith('\"')) || (val.startsWith(\"'\") && val.endsWith(\"'\"))) {\n val = val.slice(1, -1)\n }\n out[key] = val\n }\n return out\n}\n\nfunction isConfigFn(value: unknown): value is FakewareConfigFn {\n return typeof value === 'function'\n}\n\nexport async function loadConfig(opts: LoadConfigOptions = {}): Promise<LoadedConfig> {\n const cwd = opts.cwd ?? process.cwd()\n const configPath = opts.configFile\n ? isAbsolute(opts.configFile)\n ? opts.configFile\n : resolve(cwd, opts.configFile)\n : await findConfig(cwd)\n const projectRoot = dirname(configPath)\n\n const env: Record<string, string | undefined> = {\n ...process.env,\n ...(await readEnvFile(projectRoot)),\n }\n\n const mod = await loadModule<{ default?: unknown }>(configPath)\n const exported = mod.default\n if (exported === undefined) {\n throw new ConfigError(`${configPath} must \\`export default defineConfig(...)\\`.`)\n }\n\n const configEnv: ConfigEnv = { env, mode: opts.mode ?? 'development' }\n const raw = isConfigFn(exported) ? exported(configEnv) : (exported as FakewareUserConfig)\n\n const interpolated = interpolate(raw, env)\n\n const parsed = fakewareConfigSchema.safeParse(interpolated)\n if (!parsed.success) {\n throw new ConfigError(`Invalid config in ${configPath}: ${parsed.error.message}`)\n }\n\n const { shopware } = parsed.data\n if (!shopware) {\n throw new ConfigError(\n `No \\`shopware\\` connection configured in ${configPath}. up/down need a shop to talk to.`,\n )\n }\n\n return { config: parsed.data, connection: shopware, configPath, projectRoot }\n}\n"],"mappings":";;;;;AAEA,MAAM,kBACJ;AAEF,IAAa,kBAAb,cAAqC,MAAM,CAAC;AAE5C,SAAS,QAAiB;CACxB,OAAO,OAAQ,WAAiC,QAAQ;AAC1D;AAEA,SAAS,kBAA2B;CAClC,MAAM,UAAW,QAAQ,SAAsC;CAC/D,OAAO,YAAY,WAAW,YAAY;AAC5C;AAEA,eAAsB,WAAwB,SAA6B;CACzE,IAAI,CAAC,MAAM,KAAK,CAAC,gBAAgB,GAC/B,MAAM,IAAI,gBAAgB,eAAe;CAE3C,IAAI;EACF,OAAQ,MAAM,OAAO,cAAc,OAAO,EAAE;CAC9C,SAAS,OAAO;EACd,MAAM,IAAI,gBACR,kBAAkB,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACrF;CACF;AACF;;;AChBA,SAAgB,aACd,QACuC;CACvC,OAAO;AACT;;;ACfA,IAAa,cAAb,cAAiC,MAAM,CAAC;;;ACExC,MAAM,UAAU;AAEhB,SAAgB,YAAe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M,SAAS,qBAAqB,UAAU,YAAY;CAC1D,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,YAAY,qBAAqB,WAAW,IAAI,OAAO,MAAM,SAAS;CAGlF,MAAM,EAAE,aAAa,OAAO;CAC5B,IAAI,CAAC,UACH,MAAM,IAAI,YACR,4CAA4C,WAAW,kCACzD;CAGF,OAAO;EAAE,QAAQ,OAAO;EAAM,YAAY;EAAU;EAAY;CAAY;AAC9E"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createAdminAPIClient } from "@shopware/api-client";
|
|
2
|
+
import { operations } from "@shopware/api-client/admin-api-types";
|
|
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 toConnectionError(connection: ShopwareConnection, error: unknown): ShopwareConnectionError;
|
|
24
|
+
declare function validateConnection(connection: ShopwareConnection): Promise<void>;
|
|
25
|
+
declare function fetchShopInfo(connection: ShopwareConnection): Promise<ShopInfo>;
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/domain/sink.d.ts
|
|
28
|
+
type SinkRecord = Record<string, unknown> & {
|
|
29
|
+
id: string;
|
|
30
|
+
};
|
|
31
|
+
interface ShopwareSink {
|
|
32
|
+
upsert(entity: string, records: SinkRecord[]): Promise<void>;
|
|
33
|
+
delete(entity: string, ids: string[]): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/shopware/sink.d.ts
|
|
37
|
+
interface SyncSinkOptions {
|
|
38
|
+
client?: ShopwareClient;
|
|
39
|
+
}
|
|
40
|
+
declare function createSyncSink(connection: ShopwareConnection, options?: SyncSinkOptions): ShopwareSink;
|
|
41
|
+
//#endregion
|
|
42
|
+
export { toConnectionError as a, ShopwareClient as c, ShopwareConnection as d, fetchShopInfo as i, createShopwareClient as l, ShopwareSink as n, validateConnection as o, SinkRecord as r, ShopwareConnectionError as s, createSyncSink as t, ShopInfo as u };
|
|
43
|
+
//# sourceMappingURL=index-BZFBgKu8.d.mts.map
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { d as ShopwareConnection } from "./index-BZFBgKu8.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/config/schema.d.ts
|
|
5
|
+
declare const shopwareSchema: z.ZodObject<{
|
|
6
|
+
url: z.ZodString;
|
|
7
|
+
clientId: z.ZodString;
|
|
8
|
+
clientSecret: z.ZodString;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
declare const fakewareConfigSchema: z.ZodObject<{
|
|
11
|
+
shopware: z.ZodOptional<z.ZodObject<{
|
|
12
|
+
url: z.ZodString;
|
|
13
|
+
clientId: z.ZodString;
|
|
14
|
+
clientSecret: z.ZodString;
|
|
15
|
+
}, z.core.$strip>>;
|
|
16
|
+
}, z.core.$strip>;
|
|
17
|
+
type FakewareConfig = z.output<typeof fakewareConfigSchema>;
|
|
18
|
+
type FakewareUserConfig = z.input<typeof fakewareConfigSchema>;
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/config/define.d.ts
|
|
21
|
+
interface ConfigEnv {
|
|
22
|
+
env: Record<string, string | undefined>;
|
|
23
|
+
mode: string;
|
|
24
|
+
}
|
|
25
|
+
type FakewareConfigFn = (env: ConfigEnv) => FakewareUserConfig;
|
|
26
|
+
declare function defineConfig(config: FakewareUserConfig): FakewareUserConfig;
|
|
27
|
+
declare function defineConfig(config: FakewareConfigFn): FakewareConfigFn;
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/config/errors.d.ts
|
|
30
|
+
declare class ConfigError extends Error {}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/config/interpolate.d.ts
|
|
33
|
+
declare function interpolate<T>(value: T, env: Record<string, string | undefined>): T;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/config/load.d.ts
|
|
36
|
+
declare const DEFAULT_CONFIG_FILENAME = "fakeware.config.ts";
|
|
37
|
+
interface LoadConfigOptions {
|
|
38
|
+
cwd?: string;
|
|
39
|
+
configFile?: string;
|
|
40
|
+
mode?: string;
|
|
41
|
+
}
|
|
42
|
+
interface LoadedConfig {
|
|
43
|
+
config: FakewareConfig;
|
|
44
|
+
connection: ShopwareConnection;
|
|
45
|
+
configPath: string;
|
|
46
|
+
projectRoot: string;
|
|
47
|
+
}
|
|
48
|
+
declare function loadConfig(opts?: LoadConfigOptions): Promise<LoadedConfig>;
|
|
49
|
+
//#endregion
|
|
50
|
+
export { interpolate as a, FakewareConfigFn as c, FakewareUserConfig as d, fakewareConfigSchema as f, loadConfig as i, defineConfig as l, LoadConfigOptions as n, ConfigError as o, shopwareSchema as p, LoadedConfig as r, ConfigEnv as s, DEFAULT_CONFIG_FILENAME as t, FakewareConfig as u };
|
|
51
|
+
//# sourceMappingURL=index-Dpb1t7ns.d.mts.map
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { r as LoadedConfig } from "./index-Dpb1t7ns.mjs";
|
|
2
|
+
import { n as ShopwareSink, r as SinkRecord } from "./index-BZFBgKu8.mjs";
|
|
3
|
+
import { Schemas } from "@shopware/api-client/admin-api-types";
|
|
4
|
+
|
|
5
|
+
//#region src/define/ctx.d.ts
|
|
6
|
+
interface Ctx {
|
|
7
|
+
index: number;
|
|
8
|
+
count: number;
|
|
9
|
+
ref(path: string): string;
|
|
10
|
+
refs(entity: string): string[];
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/define/schema.d.ts
|
|
14
|
+
type Words<S extends string, Cur extends string = '', Acc extends string[] = []> = S extends `${infer H}${infer T}` ? H extends Uppercase<H> ? Cur extends '' ? Words<T, H, Acc> : Words<T, H, [...Acc, Cur]> : Words<T, `${Cur}${H}`, Acc> : Cur extends '' ? Acc : [...Acc, Cur];
|
|
15
|
+
type JoinSnake<T extends string[]> = T extends [infer A extends string, ...infer R extends string[]] ? R extends [] ? Lowercase<A> : `${Lowercase<A>}_${JoinSnake<R>}` : '';
|
|
16
|
+
type SnakeOfPascal<S extends string> = JoinSnake<Words<S>>;
|
|
17
|
+
type EntityKey = { [K in keyof Schemas]: K extends `${string}JsonApi` ? never : K extends Capitalize<K & string> ? Schemas[K] extends {
|
|
18
|
+
id?: string;
|
|
19
|
+
} ? K : never : never }[keyof Schemas] & string;
|
|
20
|
+
type EntityNameToKey = { [K in EntityKey as SnakeOfPascal<K>]: K };
|
|
21
|
+
type EntityName = keyof EntityNameToKey & string;
|
|
22
|
+
type SchemaOf<E extends EntityName> = Schemas[EntityNameToKey[E]];
|
|
23
|
+
type Equal<X, Y> = (<G>() => G extends X ? 1 : 2) extends (<G>() => G extends Y ? 1 : 2) ? true : false;
|
|
24
|
+
type IsWritable<T, K extends keyof T> = Equal<{ [Q in K]: T[K] }, { -readonly [Q in K]: T[K] }>;
|
|
25
|
+
type NoiseField = 'extensions' | 'translated' | 'customFields' | `${string}Ro`;
|
|
26
|
+
type WritableKeys<T> = { [K in keyof T]-?: K extends NoiseField ? never : IsWritable<T, K> extends true ? K : never }[keyof T];
|
|
27
|
+
type AssocObject<T> = ('id' extends keyof T ? {
|
|
28
|
+
id?: string;
|
|
29
|
+
} : object) & { [K in keyof T]?: unknown };
|
|
30
|
+
type AssocElement<U> = U extends object ? AssocObject<U> : U;
|
|
31
|
+
type Field<T> = T extends (infer U)[] ? Producible<AssocElement<U>>[] : T extends string | number | boolean | null ? T : T extends object ? AssocObject<T> : T;
|
|
32
|
+
type Producible<T> = Field<T> | ((ctx: Ctx) => Field<T>);
|
|
33
|
+
type RecordShape<E extends EntityName> = {
|
|
34
|
+
$key?: string;
|
|
35
|
+
} & { [K in WritableKeys<SchemaOf<E>>]?: Producible<SchemaOf<E>[K]> };
|
|
36
|
+
type DefineRecord<E extends EntityName> = RecordShape<E> | ((ctx: Ctx) => RecordShape<E>);
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/define/define.d.ts
|
|
39
|
+
declare function define<const E extends EntityName>(entity: E, records: DefineRecord<E> | readonly DefineRecord<E>[]): void;
|
|
40
|
+
declare function many<R extends Record<string, unknown>>(n: number, fn: (ctx: Ctx) => R): R;
|
|
41
|
+
declare function ref(path: string): string;
|
|
42
|
+
declare function refs(entity: string): string[];
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/define/errors.d.ts
|
|
45
|
+
declare class RefError extends Error {}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/engine/errors.d.ts
|
|
48
|
+
declare class GraphError extends Error {}
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/engine/manifest.d.ts
|
|
51
|
+
interface ManifestRecord {
|
|
52
|
+
id: string;
|
|
53
|
+
hash: string;
|
|
54
|
+
}
|
|
55
|
+
interface ManifestEntity {
|
|
56
|
+
entity: string;
|
|
57
|
+
records: ManifestRecord[];
|
|
58
|
+
}
|
|
59
|
+
interface Manifest {
|
|
60
|
+
version: 1;
|
|
61
|
+
fakewareVersion: string;
|
|
62
|
+
createdAt: string;
|
|
63
|
+
shopwareUrl: string;
|
|
64
|
+
entities: ManifestEntity[];
|
|
65
|
+
checksum: string;
|
|
66
|
+
}
|
|
67
|
+
declare function readManifest(projectRoot: string, shopwareUrl: string): Promise<Manifest | null>;
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/engine/run.d.ts
|
|
70
|
+
interface Reporter {
|
|
71
|
+
onStart?(entity: string): void;
|
|
72
|
+
onStep?(step: ReportStep): void;
|
|
73
|
+
}
|
|
74
|
+
interface ReportStep {
|
|
75
|
+
entity: string;
|
|
76
|
+
created: number;
|
|
77
|
+
updated: number;
|
|
78
|
+
unchanged: number;
|
|
79
|
+
deleted: number;
|
|
80
|
+
}
|
|
81
|
+
interface RunOptions {
|
|
82
|
+
loaded: LoadedConfig;
|
|
83
|
+
sink: ShopwareSink;
|
|
84
|
+
dryRun?: boolean;
|
|
85
|
+
reporter?: Reporter;
|
|
86
|
+
fakewareVersion?: string;
|
|
87
|
+
now?: string;
|
|
88
|
+
}
|
|
89
|
+
interface UpResult {
|
|
90
|
+
steps: ReportStep[];
|
|
91
|
+
manifestWritten: boolean;
|
|
92
|
+
}
|
|
93
|
+
interface DownResult {
|
|
94
|
+
steps: ReportStep[];
|
|
95
|
+
reverted: boolean;
|
|
96
|
+
}
|
|
97
|
+
declare function runUp(opts: RunOptions): Promise<UpResult>;
|
|
98
|
+
declare function runDown(opts: RunOptions): Promise<DownResult>;
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/runtime/load-module.d.ts
|
|
101
|
+
declare class LoadModuleError extends Error {}
|
|
102
|
+
//#endregion
|
|
103
|
+
export { type Ctx, type DefineRecord, type DownResult, type EntityName, GraphError, LoadModuleError, type Manifest, type ManifestEntity, type ManifestRecord, RefError, type ReportStep, type Reporter, type RunOptions, type ShopwareSink, type SinkRecord, type UpResult, define, many, readManifest, ref, refs, runDown, runUp };
|
|
104
|
+
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { c as LoadModuleError, l as loadModule, o as ConfigError } from "./config-CSPA4Itj.mjs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
//#region src/define/errors.ts
|
|
6
|
+
var RefError = class extends Error {};
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/define/is-plain-object.ts
|
|
9
|
+
function isPlainObject(value) {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/define/ids.ts
|
|
14
|
+
const FAKEWARE_NAMESPACE = "b1e0a3f4-6c2d-5a8b-9e7f-0d1c2b3a4e5f";
|
|
15
|
+
function uuidBytes(uuid) {
|
|
16
|
+
const hex = uuid.replace(/-/g, "");
|
|
17
|
+
const bytes = new Uint8Array(16);
|
|
18
|
+
for (let i = 0; i < 16; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
const NAMESPACE_BYTES = uuidBytes(FAKEWARE_NAMESPACE);
|
|
22
|
+
function uuidv5(name) {
|
|
23
|
+
const hash = createHash("sha1");
|
|
24
|
+
hash.update(NAMESPACE_BYTES);
|
|
25
|
+
hash.update(name, "utf8");
|
|
26
|
+
const bytes = hash.digest().subarray(0, 16);
|
|
27
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
28
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
29
|
+
return bytes.toString("hex");
|
|
30
|
+
}
|
|
31
|
+
function deterministicId(entity, key) {
|
|
32
|
+
return uuidv5(`${entity}:${key}`);
|
|
33
|
+
}
|
|
34
|
+
function canonicalize(value) {
|
|
35
|
+
if (Array.isArray(value)) return value.map(canonicalize);
|
|
36
|
+
if (isPlainObject(value)) {
|
|
37
|
+
const sorted = {};
|
|
38
|
+
for (const k of Object.keys(value).sort()) sorted[k] = canonicalize(value[k]);
|
|
39
|
+
return sorted;
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function recordHash(payload) {
|
|
44
|
+
return createHash("sha256").update(JSON.stringify(canonicalize(payload))).digest("hex");
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/define/registry.ts
|
|
48
|
+
let entries = [];
|
|
49
|
+
function resetRegistry() {
|
|
50
|
+
entries = [];
|
|
51
|
+
}
|
|
52
|
+
function staticKey(value) {
|
|
53
|
+
if (typeof value !== "function") {
|
|
54
|
+
const k = value.$key;
|
|
55
|
+
if (typeof k === "string") return k;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function defineRecords(entity, recordOrRecords) {
|
|
59
|
+
const list = Array.isArray(recordOrRecords) ? recordOrRecords : [recordOrRecords];
|
|
60
|
+
for (const value of list) entries.push({
|
|
61
|
+
entity,
|
|
62
|
+
key: staticKey(value),
|
|
63
|
+
value
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function drain() {
|
|
67
|
+
const order = [];
|
|
68
|
+
const byEntity = /* @__PURE__ */ new Map();
|
|
69
|
+
for (const e of entries) {
|
|
70
|
+
let bucket = byEntity.get(e.entity);
|
|
71
|
+
if (!bucket) {
|
|
72
|
+
bucket = [];
|
|
73
|
+
byEntity.set(e.entity, bucket);
|
|
74
|
+
order.push(e.entity);
|
|
75
|
+
}
|
|
76
|
+
bucket.push(e);
|
|
77
|
+
}
|
|
78
|
+
return order.map((entity) => ({
|
|
79
|
+
entity,
|
|
80
|
+
entries: byEntity.get(entity)
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
function buildRefIndex(drained) {
|
|
84
|
+
const refIndex = { byEntity: /* @__PURE__ */ new Map() };
|
|
85
|
+
const ids = /* @__PURE__ */ new Map();
|
|
86
|
+
for (const { entity, entries: bucket } of drained) {
|
|
87
|
+
const slot = {
|
|
88
|
+
byKey: /* @__PURE__ */ new Map(),
|
|
89
|
+
all: []
|
|
90
|
+
};
|
|
91
|
+
refIndex.byEntity.set(entity, slot);
|
|
92
|
+
bucket.forEach((entry, i) => {
|
|
93
|
+
const id = deterministicId(entity, entry.key ?? String(i));
|
|
94
|
+
ids.set(entry, id);
|
|
95
|
+
slot.all.push(id);
|
|
96
|
+
if (entry.key) slot.byKey.set(entry.key, id);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
refIndex,
|
|
101
|
+
ids
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/define/define.ts
|
|
106
|
+
function define(entity, records) {
|
|
107
|
+
defineRecords(entity, records);
|
|
108
|
+
}
|
|
109
|
+
function many(n, fn) {
|
|
110
|
+
return Array.from({ length: n }, () => fn);
|
|
111
|
+
}
|
|
112
|
+
let active;
|
|
113
|
+
function setActiveRefIndex(refIndex) {
|
|
114
|
+
active = refIndex;
|
|
115
|
+
}
|
|
116
|
+
function requireActive() {
|
|
117
|
+
if (!active) throw new RefError("ref()/refs() may only be called while resolving definitions.");
|
|
118
|
+
return active;
|
|
119
|
+
}
|
|
120
|
+
function ref(path) {
|
|
121
|
+
const slash = path.indexOf("/");
|
|
122
|
+
if (slash === -1) throw new RefError(`ref('${path}') must be of the form 'entity/key'.`);
|
|
123
|
+
const entity = path.slice(0, slash);
|
|
124
|
+
const key = path.slice(slash + 1);
|
|
125
|
+
const id = requireActive().byEntity.get(entity)?.byKey.get(key);
|
|
126
|
+
if (!id) throw new RefError(`ref('${path}') does not match any defined record.`);
|
|
127
|
+
return id;
|
|
128
|
+
}
|
|
129
|
+
function refs(entity) {
|
|
130
|
+
const slot = requireActive().byEntity.get(entity);
|
|
131
|
+
if (!slot) throw new RefError(`refs('${entity}') does not match any defined entity.`);
|
|
132
|
+
return [...slot.all];
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/define/resolve.ts
|
|
136
|
+
function resolveValue(value, ctx) {
|
|
137
|
+
if (typeof value === "function") return resolveValue(value(ctx), ctx);
|
|
138
|
+
if (Array.isArray(value)) return value.map((item) => resolveValue(item, ctx));
|
|
139
|
+
if (isPlainObject(value)) {
|
|
140
|
+
const out = {};
|
|
141
|
+
for (const [key, v] of Object.entries(value)) {
|
|
142
|
+
if (key === "$key") continue;
|
|
143
|
+
out[key] = resolveValue(v, ctx);
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
return value;
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/engine/errors.ts
|
|
151
|
+
var GraphError = class extends Error {};
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/engine/build-graph.ts
|
|
154
|
+
function ownerByIdOf(refIndex) {
|
|
155
|
+
const owner = /* @__PURE__ */ new Map();
|
|
156
|
+
for (const [entity, slot] of refIndex.byEntity) for (const id of slot.all) owner.set(id, entity);
|
|
157
|
+
return owner;
|
|
158
|
+
}
|
|
159
|
+
function collectIdRefs(value, ownerById, into) {
|
|
160
|
+
if (typeof value === "string") {
|
|
161
|
+
const owner = ownerById.get(value);
|
|
162
|
+
if (owner) into.add(owner);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (Array.isArray(value)) {
|
|
166
|
+
for (const item of value) collectIdRefs(item, ownerById, into);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (isPlainObject(value)) for (const v of Object.values(value)) collectIdRefs(v, ownerById, into);
|
|
170
|
+
}
|
|
171
|
+
function topoSort(entities, edges) {
|
|
172
|
+
const indegree = new Map(entities.map((e) => [e, 0]));
|
|
173
|
+
const dependents = new Map(entities.map((e) => [e, []]));
|
|
174
|
+
for (const [entity, deps] of edges) for (const dep of deps) {
|
|
175
|
+
indegree.set(entity, (indegree.get(entity) ?? 0) + 1);
|
|
176
|
+
dependents.get(dep)?.push(entity);
|
|
177
|
+
}
|
|
178
|
+
const queue = entities.filter((e) => (indegree.get(e) ?? 0) === 0);
|
|
179
|
+
const ordered = [];
|
|
180
|
+
while (queue.length > 0) {
|
|
181
|
+
const entity = queue.shift();
|
|
182
|
+
ordered.push(entity);
|
|
183
|
+
for (const dependent of dependents.get(entity) ?? []) {
|
|
184
|
+
const next = (indegree.get(dependent) ?? 0) - 1;
|
|
185
|
+
indegree.set(dependent, next);
|
|
186
|
+
if (next === 0) queue.push(dependent);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (ordered.length !== entities.length) throw new GraphError(`Reference cycle between entities: ${entities.filter((e) => !ordered.includes(e)).join(", ")}.`);
|
|
190
|
+
return ordered;
|
|
191
|
+
}
|
|
192
|
+
function buildWritePlan(drained) {
|
|
193
|
+
const { refIndex, ids } = buildRefIndex(drained);
|
|
194
|
+
const ownerById = ownerByIdOf(refIndex);
|
|
195
|
+
const entities = drained.map((d) => d.entity);
|
|
196
|
+
const records = /* @__PURE__ */ new Map();
|
|
197
|
+
const edges = new Map(entities.map((e) => [e, /* @__PURE__ */ new Set()]));
|
|
198
|
+
setActiveRefIndex(refIndex);
|
|
199
|
+
try {
|
|
200
|
+
for (const { entity, entries } of drained) {
|
|
201
|
+
const out = [];
|
|
202
|
+
entries.forEach((entry, i) => {
|
|
203
|
+
const ctx = {
|
|
204
|
+
index: i,
|
|
205
|
+
count: entries.length,
|
|
206
|
+
ref,
|
|
207
|
+
refs
|
|
208
|
+
};
|
|
209
|
+
const payload = resolveValue(entry.value, ctx);
|
|
210
|
+
const id = ids.get(entry);
|
|
211
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
212
|
+
collectIdRefs(payload, ownerById, referenced);
|
|
213
|
+
for (const dep of referenced) if (dep !== entity) edges.get(entity)?.add(dep);
|
|
214
|
+
out.push({
|
|
215
|
+
...payload,
|
|
216
|
+
id
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
records.set(entity, out);
|
|
220
|
+
}
|
|
221
|
+
} finally {
|
|
222
|
+
setActiveRefIndex(void 0);
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
order: topoSort(entities, edges),
|
|
226
|
+
records
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/engine/discover.ts
|
|
231
|
+
const DATA_DIR = "data";
|
|
232
|
+
function isDataFile(name) {
|
|
233
|
+
return name.endsWith(".ts") && !name.endsWith(".test.ts") && !name.endsWith(".d.ts");
|
|
234
|
+
}
|
|
235
|
+
async function discoverDataFiles(projectRoot) {
|
|
236
|
+
const root = join(projectRoot, DATA_DIR);
|
|
237
|
+
let names;
|
|
238
|
+
try {
|
|
239
|
+
names = await readdir(root, { recursive: true });
|
|
240
|
+
} catch {
|
|
241
|
+
return [];
|
|
242
|
+
}
|
|
243
|
+
return names.filter(isDataFile).sort().map((name) => join(root, name));
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/engine/evaluate.ts
|
|
247
|
+
async function evaluateDataFiles(files) {
|
|
248
|
+
resetRegistry();
|
|
249
|
+
for (const file of files) await loadModule(file);
|
|
250
|
+
return drain();
|
|
251
|
+
}
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/engine/manifest.ts
|
|
254
|
+
const MANIFEST_DIR = ".fakeware";
|
|
255
|
+
const CURRENT_VERSION = 1;
|
|
256
|
+
function shopKey(shopwareUrl) {
|
|
257
|
+
return createHash("sha256").update(shopwareUrl).digest("hex").slice(0, 16);
|
|
258
|
+
}
|
|
259
|
+
function manifestPath(projectRoot, shopwareUrl) {
|
|
260
|
+
return join(projectRoot, MANIFEST_DIR, `${shopKey(shopwareUrl)}.json`);
|
|
261
|
+
}
|
|
262
|
+
function checksumOf(entities) {
|
|
263
|
+
const canonical = entities.map((e) => ({
|
|
264
|
+
entity: e.entity,
|
|
265
|
+
records: [...e.records].sort((a, b) => a.id.localeCompare(b.id))
|
|
266
|
+
})).sort((a, b) => a.entity.localeCompare(b.entity));
|
|
267
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
268
|
+
}
|
|
269
|
+
function buildManifest(input) {
|
|
270
|
+
return {
|
|
271
|
+
version: CURRENT_VERSION,
|
|
272
|
+
fakewareVersion: input.fakewareVersion,
|
|
273
|
+
createdAt: input.createdAt,
|
|
274
|
+
shopwareUrl: input.shopwareUrl,
|
|
275
|
+
entities: input.entities,
|
|
276
|
+
checksum: checksumOf(input.entities)
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
async function readManifest(projectRoot, shopwareUrl) {
|
|
280
|
+
const path = manifestPath(projectRoot, shopwareUrl);
|
|
281
|
+
let contents;
|
|
282
|
+
try {
|
|
283
|
+
contents = await readFile(path, "utf8");
|
|
284
|
+
} catch {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
const parsed = JSON.parse(contents);
|
|
288
|
+
switch (parsed.version) {
|
|
289
|
+
case CURRENT_VERSION: {
|
|
290
|
+
const manifest = parsed;
|
|
291
|
+
if (checksumOf(manifest.entities) !== manifest.checksum) throw new ConfigError(`Manifest at ${path} is corrupt (checksum mismatch). Re-run \`fakeware up\`.`);
|
|
292
|
+
return manifest;
|
|
293
|
+
}
|
|
294
|
+
default: throw new ConfigError(`Unsupported manifest version ${parsed.version} (this CLI understands up to ${CURRENT_VERSION}). Upgrade fakeware.`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
async function writeManifest(projectRoot, manifest) {
|
|
298
|
+
const path = manifestPath(projectRoot, manifest.shopwareUrl);
|
|
299
|
+
await mkdir(dirname(path), { recursive: true });
|
|
300
|
+
await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
301
|
+
}
|
|
302
|
+
async function removeManifest(projectRoot, shopwareUrl) {
|
|
303
|
+
await rm(manifestPath(projectRoot, shopwareUrl), { force: true });
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region src/engine/run.ts
|
|
307
|
+
function priorHashes(manifest) {
|
|
308
|
+
const map = /* @__PURE__ */ new Map();
|
|
309
|
+
for (const e of manifest?.entities ?? []) map.set(e.entity, new Map(e.records.map((r) => [r.id, r.hash])));
|
|
310
|
+
return map;
|
|
311
|
+
}
|
|
312
|
+
async function runUp(opts) {
|
|
313
|
+
const { loaded, sink, dryRun, reporter } = opts;
|
|
314
|
+
const plan = buildWritePlan(await evaluateDataFiles(await discoverDataFiles(loaded.projectRoot)));
|
|
315
|
+
const prior = priorHashes(await readManifest(loaded.projectRoot, loaded.connection.url));
|
|
316
|
+
const steps = [];
|
|
317
|
+
const manifestEntities = [];
|
|
318
|
+
for (const entity of plan.order) {
|
|
319
|
+
reporter?.onStart?.(entity);
|
|
320
|
+
const records = plan.records.get(entity) ?? [];
|
|
321
|
+
const priorForEntity = prior.get(entity) ?? /* @__PURE__ */ new Map();
|
|
322
|
+
const toWrite = [];
|
|
323
|
+
let created = 0;
|
|
324
|
+
let updated = 0;
|
|
325
|
+
let unchanged = 0;
|
|
326
|
+
const manifestRecords = records.map((record) => {
|
|
327
|
+
const hash = recordHash(record);
|
|
328
|
+
const previous = priorForEntity.get(record.id);
|
|
329
|
+
if (previous === void 0) created++;
|
|
330
|
+
else if (previous === hash) unchanged++;
|
|
331
|
+
else updated++;
|
|
332
|
+
if (previous !== hash) toWrite.push(record);
|
|
333
|
+
return {
|
|
334
|
+
id: record.id,
|
|
335
|
+
hash
|
|
336
|
+
};
|
|
337
|
+
});
|
|
338
|
+
if (!dryRun && toWrite.length > 0) await sink.upsert(entity, toWrite);
|
|
339
|
+
manifestEntities.push({
|
|
340
|
+
entity,
|
|
341
|
+
records: manifestRecords
|
|
342
|
+
});
|
|
343
|
+
const step = {
|
|
344
|
+
entity,
|
|
345
|
+
created,
|
|
346
|
+
updated,
|
|
347
|
+
unchanged,
|
|
348
|
+
deleted: 0
|
|
349
|
+
};
|
|
350
|
+
steps.push(step);
|
|
351
|
+
reporter?.onStep?.(step);
|
|
352
|
+
}
|
|
353
|
+
if (!dryRun) await writeManifest(loaded.projectRoot, buildManifest({
|
|
354
|
+
fakewareVersion: opts.fakewareVersion ?? "0.0.0",
|
|
355
|
+
createdAt: opts.now ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
356
|
+
shopwareUrl: loaded.connection.url,
|
|
357
|
+
entities: manifestEntities
|
|
358
|
+
}));
|
|
359
|
+
return {
|
|
360
|
+
steps,
|
|
361
|
+
manifestWritten: !dryRun
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
async function runDown(opts) {
|
|
365
|
+
const { loaded, sink, dryRun, reporter } = opts;
|
|
366
|
+
const manifest = await readManifest(loaded.projectRoot, loaded.connection.url);
|
|
367
|
+
if (!manifest) return {
|
|
368
|
+
steps: [],
|
|
369
|
+
reverted: false
|
|
370
|
+
};
|
|
371
|
+
const steps = [];
|
|
372
|
+
for (const entity of [...manifest.entities].reverse()) {
|
|
373
|
+
reporter?.onStart?.(entity.entity);
|
|
374
|
+
const ids = entity.records.map((r) => r.id);
|
|
375
|
+
if (!dryRun && ids.length > 0) await sink.delete(entity.entity, ids);
|
|
376
|
+
const step = {
|
|
377
|
+
entity: entity.entity,
|
|
378
|
+
created: 0,
|
|
379
|
+
updated: 0,
|
|
380
|
+
unchanged: 0,
|
|
381
|
+
deleted: ids.length
|
|
382
|
+
};
|
|
383
|
+
steps.push(step);
|
|
384
|
+
reporter?.onStep?.(step);
|
|
385
|
+
}
|
|
386
|
+
if (!dryRun) await removeManifest(loaded.projectRoot, loaded.connection.url);
|
|
387
|
+
return {
|
|
388
|
+
steps,
|
|
389
|
+
reverted: !dryRun
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
//#endregion
|
|
393
|
+
export { GraphError, LoadModuleError, RefError, define, many, readManifest, ref, refs, runDown, runUp };
|
|
394
|
+
|
|
395
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -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","export class GraphError extends Error {}\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 { ShopwareSink, SinkRecord } from '../domain'\nimport { buildWritePlan } from './build-graph'\nimport { discoverDataFiles } from './discover'\nimport { evaluateDataFiles } from './evaluate'\nimport {\n buildManifest,\n type Manifest,\n type ManifestEntity,\n readManifest,\n removeManifest,\n writeManifest,\n} from './manifest'\n\nexport interface Reporter {\n onStart?(entity: string): void\n onStep?(step: ReportStep): void\n}\n\nexport interface ReportStep {\n entity: string\n created: number\n updated: number\n unchanged: number\n deleted: number\n}\n\nexport interface RunOptions {\n loaded: LoadedConfig\n sink: ShopwareSink\n dryRun?: boolean\n reporter?: Reporter\n fakewareVersion?: string\n now?: string\n}\n\nexport interface UpResult {\n steps: ReportStep[]\n manifestWritten: boolean\n}\n\nexport interface DownResult {\n steps: ReportStep[]\n reverted: boolean\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\nexport async function runUp(opts: RunOptions): Promise<UpResult> {\n const { loaded, sink, dryRun, reporter } = 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 const steps: ReportStep[] = []\n const manifestEntities: ManifestEntity[] = []\n\n for (const entity of plan.order) {\n reporter?.onStart?.(entity)\n const records = plan.records.get(entity) ?? []\n const priorForEntity = prior.get(entity) ?? new Map<string, string>()\n const toWrite: SinkRecord[] = []\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 = priorForEntity.get(record.id)\n if (previous === undefined) created++\n else if (previous === hash) unchanged++\n else updated++\n if (previous !== hash) toWrite.push(record)\n return { id: record.id, hash }\n })\n\n if (!dryRun && toWrite.length > 0) {\n await sink.upsert(entity, toWrite)\n }\n\n manifestEntities.push({ entity, records: manifestRecords })\n const step: ReportStep = { entity, created, updated, unchanged, deleted: 0 }\n steps.push(step)\n reporter?.onStep?.(step)\n }\n\n if (!dryRun) {\n await 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: manifestEntities,\n }),\n )\n }\n\n return { steps, manifestWritten: !dryRun }\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 const steps: ReportStep[] = []\n for (const entity of [...manifest.entities].reverse()) {\n reporter?.onStart?.(entity.entity)\n const ids = entity.records.map((r) => r.id)\n if (!dryRun && ids.length > 0) {\n await sink.delete(entity.entity, ids)\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,EAAE,SAAS,GAAG,EAAE;CACnC,MAAM,KAAO,MAAM,KAAgB,KAAQ;CAC3C,MAAM,KAAO,MAAM,KAAgB,KAAQ;CAE3C,OAAO,MAAM,SAAS,KAAK;AAC7B;AAEA,SAAgB,gBAAgB,QAAgB,KAAqB;CACnE,OAAO,OAAO,GAAG,OAAO,GAA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-
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 { a as toConnectionError, c as ShopwareClient, d as ShopwareConnection, i as fetchShopInfo, l as createShopwareClient, o as validateConnection, s as ShopwareConnectionError, t as createSyncSink, u as ShopInfo } from "../index-BZFBgKu8.mjs";
|
|
2
|
+
export { type ShopInfo, type ShopwareClient, type ShopwareConnection, ShopwareConnectionError, createShopwareClient, createSyncSink, fetchShopInfo, toConnectionError, validateConnection };
|
package/dist/shopware/index.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
import { ApiClientError, createAdminAPIClient } from "@shopware/api-client";
|
|
2
3
|
//#region src/shopware/client.ts
|
|
4
|
+
const REQUEST_TIMEOUT_MS = 12e4;
|
|
3
5
|
function createShopwareClient(connection) {
|
|
4
6
|
return createAdminAPIClient({
|
|
5
7
|
baseURL: `${connection.url.replace(/\/$/, "")}/api`,
|
|
@@ -7,7 +9,8 @@ function createShopwareClient(connection) {
|
|
|
7
9
|
grant_type: "client_credentials",
|
|
8
10
|
client_id: connection.clientId,
|
|
9
11
|
client_secret: connection.clientSecret
|
|
10
|
-
}
|
|
12
|
+
},
|
|
13
|
+
fetchOptions: { timeout: REQUEST_TIMEOUT_MS }
|
|
11
14
|
});
|
|
12
15
|
}
|
|
13
16
|
//#endregion
|
|
@@ -16,6 +19,15 @@ var ShopwareConnectionError = class extends Error {};
|
|
|
16
19
|
//#endregion
|
|
17
20
|
//#region src/shopware/locale.ts
|
|
18
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
|
+
}
|
|
19
31
|
function toShopInfo(rows) {
|
|
20
32
|
const seen = /* @__PURE__ */ new Set();
|
|
21
33
|
const locales = [];
|
|
@@ -44,6 +56,14 @@ function safeJsonParse(input) {
|
|
|
44
56
|
return null;
|
|
45
57
|
}
|
|
46
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
|
+
}
|
|
47
67
|
function missingPrivileges(error) {
|
|
48
68
|
for (const e of error.details.errors) {
|
|
49
69
|
if (e.code !== "FRAMEWORK__MISSING_PRIVILEGE_ERROR" || !e.detail) continue;
|
|
@@ -52,9 +72,20 @@ function missingPrivileges(error) {
|
|
|
52
72
|
}
|
|
53
73
|
return [];
|
|
54
74
|
}
|
|
75
|
+
function validationMessages(error) {
|
|
76
|
+
return error.details.errors.map((e) => {
|
|
77
|
+
const field = e.source?.pointer?.replace(/^\/\d+\/\d+\//, "");
|
|
78
|
+
const detail = e.detail ?? e.title ?? "Invalid value.";
|
|
79
|
+
return field ? `${field}: ${detail}` : detail;
|
|
80
|
+
}).filter((message, index, all) => all.indexOf(message) === index);
|
|
81
|
+
}
|
|
55
82
|
function toConnectionError(connection, error) {
|
|
83
|
+
if (isTimeoutError(error)) return new ShopwareConnectionError(`${connection.url} did not respond within ${REQUEST_TIMEOUT_MS / 1e3}s, the shop may be slow or unreachable.`);
|
|
56
84
|
if (error instanceof ApiClientError) switch (error.status) {
|
|
57
|
-
case 400:
|
|
85
|
+
case 400: {
|
|
86
|
+
const messages = validationMessages(error);
|
|
87
|
+
return new ShopwareConnectionError(messages.length ? `Shopware rejected the data — ${messages.join(" ")}` : `Shopware rejected the request (HTTP 400) from ${connection.url}.`);
|
|
88
|
+
}
|
|
58
89
|
case 401: return new ShopwareConnectionError("Authentication failed — check the client ID and client secret of your integration.");
|
|
59
90
|
case 403: {
|
|
60
91
|
const missing = missingPrivileges(error);
|
|
@@ -83,12 +114,45 @@ async function fetchShopInfo(connection) {
|
|
|
83
114
|
associations: { locale: {} },
|
|
84
115
|
limit: 500
|
|
85
116
|
} });
|
|
86
|
-
return toShopInfo(data.data ?? []);
|
|
117
|
+
return toShopInfo(parseLanguageRows(data.data ?? []));
|
|
87
118
|
} catch (error) {
|
|
88
119
|
throw toConnectionError(connection, error);
|
|
89
120
|
}
|
|
90
121
|
}
|
|
91
122
|
//#endregion
|
|
92
|
-
|
|
123
|
+
//#region src/shopware/sink.ts
|
|
124
|
+
const SYNC_BATCH_SIZE = 50;
|
|
125
|
+
function chunk(items, size) {
|
|
126
|
+
const out = [];
|
|
127
|
+
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
function createSyncSink(connection, options = {}) {
|
|
131
|
+
const client = options.client ?? createShopwareClient(connection);
|
|
132
|
+
async function sync(entity, action, payload) {
|
|
133
|
+
for (const batch of chunk(payload, SYNC_BATCH_SIZE)) try {
|
|
134
|
+
await client.invoke("sync post /_action/sync", {
|
|
135
|
+
headers: { "indexing-behavior": "use-queue-indexing" },
|
|
136
|
+
body: [{
|
|
137
|
+
entity,
|
|
138
|
+
action,
|
|
139
|
+
payload: batch
|
|
140
|
+
}]
|
|
141
|
+
});
|
|
142
|
+
} catch (error) {
|
|
143
|
+
throw toConnectionError(connection, error);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
async upsert(entity, records) {
|
|
148
|
+
if (records.length > 0) await sync(entity, "upsert", records);
|
|
149
|
+
},
|
|
150
|
+
async delete(entity, ids) {
|
|
151
|
+
if (ids.length > 0) await sync(entity, "delete", ids.map((id) => ({ id })));
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
export { ShopwareConnectionError, createShopwareClient, createSyncSink, fetchShopInfo, toConnectionError, validateConnection };
|
|
93
157
|
|
|
94
158
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
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,IAA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,SAAS,OAAO;EACd,MAAM,kBAAkB,YAAY,KAAK;CAC3C;AACF;AAEA,eAAsB,cAAc,YAAmD;CACrF,MAAM,SAAS,qBAAqB,UAAU;CAC9C,IAAI;EACF,MAAM,EAAE,SAAS,MAAM,OAAO,OAAO,wCAAwC,EAC3E,MAAM;GAAE,cAAc,EAAE,QAAQ,CAAC,EAAE;GAAG,OAAO;EAAI,EACnD,CAAC;EACD,OAAO,WAAY,KAAK,QAAQ,CAAC,CAAmB;CACtD,SAAS,OAAO;EACd,MAAM,kBAAkB,YAAY,KAAK;CAC3C;AACF"}
|
|
1
|
+
{"version":3,"file":"index.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 validationMessages(error: ApiClientError<{ errors: ApiError[] }>): string[] {\n return error.details.errors\n .map((e) => {\n const field = e.source?.pointer?.replace(/^\\/\\d+\\/\\d+\\//, '')\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 return new ShopwareConnectionError(\n messages.length\n ? `Shopware rejected the data — ${messages.join(' ')}`\n : `Shopware rejected the request (HTTP 400) from ${connection.url}.`,\n )\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 { ShopwareSink, SinkRecord } 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\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 ): Promise<void> {\n for (const batch of chunk(payload, SYNC_BATCH_SIZE)) {\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 }\n }\n\n return {\n async upsert(entity: string, records: SinkRecord[]): Promise<void> {\n if (records.length > 0) await sync(entity, 'upsert', records)\n },\n async delete(entity: string, ids: string[]): Promise<void> {\n if (ids.length > 0)\n await sync(\n entity,\n 'delete',\n ids.map((id) => ({ id })),\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,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ;AAC5D,CAAC;AAID,SAAgB,kBAAkB,MAA8B;CAC9D,MAAM,SAAS,EAAE,MAAM,iBAAiB,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AO,wCAAwC,EAC3E,MAAM;GAAE,cAAc,EAAE,QAAQ,CAAC,EAAE;GAAG,OAAO;EAAI,EACnD,CAAC;EACD,OAAO,WAAW,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC;CACtD,SAAS,OAAO;EACd,MAAM,kBAAkB,YAAY,KAAK;CAC3C;AACF;;;AC1GA,MAAM,kBAAkB;AAExB,SAAS,MAAS,OAAY,MAAqB;CACjD,MAAM,MAAa,CAAC;CACpB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC;CAC9E,OAAO;AACT;AAEA,SAAgB,eACd,YACA,UAA2B,CAAC,GACd;CACd,MAAM,SAAS,QAAQ,UAAU,qBAAqB,UAAU;CAEhE,eAAe,KACb,QACA,QACA,SACe;EACf,KAAK,MAAM,SAAS,MAAM,SAAS,eAAe,GAChD,IAAI;GACF,MAAM,OAAO,OAAO,2BAA2B;IAC7C,SAAS,EAAE,qBAAqB,qBAAqB;IACrD,MAAM,CAAC;KAAE;KAAQ;KAAQ,SAAS;IAAe,CAAC;GACpD,CAAC;EACH,SAAS,OAAO;GACd,MAAM,kBAAkB,YAAY,KAAK;EAC3C;CAEJ;CAEA,OAAO;EACL,MAAM,OAAO,QAAgB,SAAsC;GACjE,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,QAAQ,UAAU,OAAO;EAC9D;EACA,MAAM,OAAO,QAAgB,KAA8B;GACzD,IAAI,IAAI,SAAS,GACf,MAAM,KACJ,QACA,UACA,IAAI,KAAK,QAAQ,EAAE,GAAG,EAAE,CAC1B;EACJ;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.6",
|
|
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,10 @@
|
|
|
16
20
|
"dist"
|
|
17
21
|
],
|
|
18
22
|
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.mts",
|
|
25
|
+
"import": "./dist/index.mjs"
|
|
26
|
+
},
|
|
19
27
|
"./config": {
|
|
20
28
|
"types": "./dist/config/index.d.mts",
|
|
21
29
|
"import": "./dist/config/index.mjs"
|
|
@@ -34,5 +42,9 @@
|
|
|
34
42
|
"dependencies": {
|
|
35
43
|
"@shopware/api-client": "1.5.0",
|
|
36
44
|
"zod": "4.4.3"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@types/bun": "1.3.14",
|
|
48
|
+
"@types/node": "22.19.19"
|
|
37
49
|
}
|
|
38
50
|
}
|
|
@@ -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,E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