@dxos/config 0.8.4-main.72ec0f3 → 0.8.4-main.7ace549
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/lib/browser/index.mjs +97 -3
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node-esm/index.mjs +101 -7
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/plugin/node-esm/{chunk-C4YHC2RN.mjs → chunk-V3PJG4GW.mjs} +12 -6
- package/dist/plugin/node-esm/chunk-V3PJG4GW.mjs.map +7 -0
- package/dist/plugin/node-esm/esbuild-plugin.mjs +1 -1
- package/dist/plugin/node-esm/meta.json +1 -1
- package/dist/plugin/node-esm/rollup-plugin.mjs +1 -1
- package/dist/plugin/node-esm/vite-plugin.mjs +1 -1
- package/dist/types/src/config-service.d.ts +18 -0
- package/dist/types/src/config-service.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +10 -9
- package/src/config-service.ts +102 -0
- package/src/config.ts +3 -3
- package/src/index.ts +1 -0
- package/src/loaders/index.ts +2 -2
- package/src/plugin/definitions.ts +2 -2
- package/dist/plugin/node-esm/chunk-C4YHC2RN.mjs.map +0 -7
|
@@ -66,14 +66,20 @@ var mapToKeyValues = (spec, values) => {
|
|
|
66
66
|
};
|
|
67
67
|
var validateConfig = (config) => {
|
|
68
68
|
if (!("version" in config)) {
|
|
69
|
-
throw new InvalidConfigError(
|
|
69
|
+
throw new InvalidConfigError({
|
|
70
|
+
message: "Version not specified"
|
|
71
|
+
});
|
|
70
72
|
}
|
|
71
73
|
if (config?.version !== 1) {
|
|
72
|
-
throw new InvalidConfigError(
|
|
74
|
+
throw new InvalidConfigError({
|
|
75
|
+
message: `Invalid config version: ${config.version}`
|
|
76
|
+
});
|
|
73
77
|
}
|
|
74
78
|
const error = configRootType.protoType.verify(config);
|
|
75
79
|
if (error) {
|
|
76
|
-
throw new InvalidConfigError(
|
|
80
|
+
throw new InvalidConfigError({
|
|
81
|
+
message: String(error)
|
|
82
|
+
});
|
|
77
83
|
}
|
|
78
84
|
return config;
|
|
79
85
|
};
|
|
@@ -134,6 +140,91 @@ Config = _ts_decorate([
|
|
|
134
140
|
})
|
|
135
141
|
], Config);
|
|
136
142
|
|
|
143
|
+
// src/config-service.ts
|
|
144
|
+
import { dirname } from "@dxos/node-std/path";
|
|
145
|
+
import * as FileSystem from "@effect/platform/FileSystem";
|
|
146
|
+
import * as Context from "effect/Context";
|
|
147
|
+
import * as Effect from "effect/Effect";
|
|
148
|
+
import * as Layer from "effect/Layer";
|
|
149
|
+
import * as Option from "effect/Option";
|
|
150
|
+
import * as Yaml from "yaml";
|
|
151
|
+
import { DX_CONFIG, DX_DATA } from "@dxos/client-protocol";
|
|
152
|
+
import { getProfilePath } from "@dxos/client-protocol";
|
|
153
|
+
var memoryConfig = new Config({
|
|
154
|
+
runtime: {
|
|
155
|
+
client: {
|
|
156
|
+
edgeFeatures: {
|
|
157
|
+
echoReplicator: true,
|
|
158
|
+
feedReplicator: true,
|
|
159
|
+
signaling: true,
|
|
160
|
+
agents: true
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
var defaultConfig = new Config({
|
|
166
|
+
runtime: {
|
|
167
|
+
client: {
|
|
168
|
+
edgeFeatures: {
|
|
169
|
+
echoReplicator: true,
|
|
170
|
+
feedReplicator: true,
|
|
171
|
+
signaling: true,
|
|
172
|
+
agents: true
|
|
173
|
+
},
|
|
174
|
+
storage: {
|
|
175
|
+
persistent: true
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
services: {
|
|
179
|
+
edge: {
|
|
180
|
+
url: "wss://edge-production.dxos.workers.dev/"
|
|
181
|
+
},
|
|
182
|
+
iceProviders: [
|
|
183
|
+
{
|
|
184
|
+
urls: "https://edge-production.dxos.workers.dev/ice"
|
|
185
|
+
}
|
|
186
|
+
],
|
|
187
|
+
ai: {
|
|
188
|
+
server: "https://ai-service.dxos.workers.dev"
|
|
189
|
+
},
|
|
190
|
+
ipfs: {
|
|
191
|
+
server: "https://api.ipfs.dxos.network/api/v0",
|
|
192
|
+
gateway: "https://gateway.ipfs.dxos.network/ipfs"
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
var ConfigService = class _ConfigService extends Context.Tag("ConfigService")() {
|
|
198
|
+
static layerMemory = Layer.effect(_ConfigService, Effect.succeed(memoryConfig));
|
|
199
|
+
static load = (args) => {
|
|
200
|
+
const defaultConfigPath = `${getProfilePath(DX_CONFIG, args.profile)}.yml`;
|
|
201
|
+
return Effect.gen(function* () {
|
|
202
|
+
const fs = yield* FileSystem.FileSystem;
|
|
203
|
+
const configPath = Option.getOrElse(args.config, () => defaultConfigPath);
|
|
204
|
+
const configContent = yield* fs.readFileString(configPath);
|
|
205
|
+
const configValues = Yaml.parse(configContent);
|
|
206
|
+
return _ConfigService.of(new Config(configValues));
|
|
207
|
+
}).pipe(
|
|
208
|
+
// If the config file doesn't exist, create it.
|
|
209
|
+
Effect.catchTag("SystemError", () => Effect.gen(function* () {
|
|
210
|
+
const configValues = defaultConfig.values;
|
|
211
|
+
{
|
|
212
|
+
configValues.runtime ??= {};
|
|
213
|
+
configValues.runtime.client ??= {};
|
|
214
|
+
configValues.runtime.client.storage ??= {};
|
|
215
|
+
configValues.runtime.client.storage.dataRoot = getProfilePath(configValues.runtime.client.storage.dataRoot ?? DX_DATA, args.profile);
|
|
216
|
+
}
|
|
217
|
+
const fs = yield* FileSystem.FileSystem;
|
|
218
|
+
yield* fs.makeDirectory(dirname(defaultConfigPath), {
|
|
219
|
+
recursive: true
|
|
220
|
+
});
|
|
221
|
+
yield* fs.writeFileString(defaultConfigPath, Yaml.stringify(configValues));
|
|
222
|
+
return _ConfigService.of(new Config(configValues));
|
|
223
|
+
}))
|
|
224
|
+
);
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
|
|
137
228
|
// src/loaders/browser.js
|
|
138
229
|
import localforage from "localforage";
|
|
139
230
|
import { log } from "@dxos/log";
|
|
@@ -239,6 +330,7 @@ var configPreset = ({ edge = "main" } = {}) => new Config({
|
|
|
239
330
|
export {
|
|
240
331
|
Config,
|
|
241
332
|
ConfigResource,
|
|
333
|
+
ConfigService,
|
|
242
334
|
Defaults,
|
|
243
335
|
Dynamics,
|
|
244
336
|
Envs,
|
|
@@ -250,9 +342,11 @@ export {
|
|
|
250
342
|
SaveConfig,
|
|
251
343
|
Storage,
|
|
252
344
|
configPreset,
|
|
345
|
+
defaultConfig,
|
|
253
346
|
defs,
|
|
254
347
|
mapFromKeyValues,
|
|
255
348
|
mapToKeyValues,
|
|
349
|
+
memoryConfig,
|
|
256
350
|
validateConfig
|
|
257
351
|
};
|
|
258
352
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/index.ts", "../../../src/config.ts", "../../../src/loaders/browser.js", "../../../src/savers/browser.js", "../../../src/types.ts", "../../../src/preset.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\n// TODO(burdon): Why is this exported? (Rename).\nexport * as defs from '@dxos/protocols/proto/dxos/config';\n\nexport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport * from './config';\nexport * from './loaders';\nexport * from './savers';\nexport * from './plugin';\nexport * from './types';\nexport * from './preset';\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { boolean } from 'boolean';\nimport defaultsDeep from 'lodash.defaultsdeep';\nimport isMatch from 'lodash.ismatch';\n\nimport { InvalidConfigError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\nimport { trace } from '@dxos/tracing';\nimport { getDeep, setDeep } from '@dxos/util';\n\nimport { type ConfigKey, type DeepIndex, type ParseKey } from './types';\n\ntype MappingSpec = Record<string, { path: string; type?: string }>;\nconst configRootType = schema.getCodecForType('dxos.config.Config');\n\n/**\n * Maps the given objects onto a flattened set of (key x values).\n *\n * Expects parsed yaml content of the form:\n *\n * ```\n * ENV_VAR:\n * path: config.selector.path\n * ```\n *\n * @param {object} spec\n * @param {object} values\n * @return {object}\n */\nexport const mapFromKeyValues = (spec: MappingSpec, values: Record<string, any>) => {\n const config = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n let value = values[key];\n\n if (value !== undefined) {\n if (type) {\n switch (type) {\n case 'boolean': {\n value = boolean(value);\n break;\n }\n\n case 'number': {\n value = Number(value);\n break;\n }\n\n case 'string': {\n break;\n }\n\n case 'json': {\n value = value ? JSON.parse(value) : null;\n break;\n }\n\n default: {\n throw new Error(`Invalid type: ${type}`);\n }\n }\n }\n\n setDeep(config, path.split('.'), value);\n }\n }\n\n return config;\n};\n\n/**\n * Maps the given flattend set of (key x values) onto a JSON object.\n * @param {object} spec\n * @param {object} values\n */\nexport const mapToKeyValues = (spec: MappingSpec, values: any) => {\n const config: Record<string, any> = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n const value = getDeep(values, path.split('.'));\n if (value !== undefined) {\n switch (type) {\n case 'json':\n config[key] = JSON.stringify(value);\n break;\n default:\n config[key] = value;\n }\n }\n }\n\n return config;\n};\n\n/**\n * Validate config object.\n */\nexport const validateConfig = (config: ConfigProto): ConfigProto => {\n if (!('version' in config)) {\n throw new InvalidConfigError('Version not specified');\n }\n\n if (config?.version !== 1) {\n throw new InvalidConfigError(`Invalid config version: ${config.version}`);\n }\n\n const error = configRootType.protoType.verify(config);\n if (error) {\n throw new InvalidConfigError(error);\n }\n\n return config;\n};\n\nexport const ConfigResource = Symbol.for('dxos.resource.Config');\n\n/**\n * Global configuration object.\n * NOTE: Config objects are immutable.\n */\n@trace.resource({ annotation: ConfigResource })\nexport class Config {\n private readonly _config: any;\n\n /**\n * Creates an immutable instance.\n * @constructor\n */\n constructor(config: ConfigProto = {}, ...objects: ConfigProto[]) {\n this._config = validateConfig(defaultsDeep(config, ...objects, { version: 1 }));\n }\n\n /**\n * Returns an immutable config JSON object.\n */\n get values(): ConfigProto {\n return this._config;\n }\n\n /**\n * Returns the given config property.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n * @param defaultValue Default value to return if option is not present in the config.\n * @returns The config value or undefined if the option is not present.\n */\n get<K extends ConfigKey>(\n key: K,\n defaultValue?: DeepIndex<ConfigProto, ParseKey<K>>,\n ): DeepIndex<ConfigProto, ParseKey<K>> | undefined {\n return getDeep(this._config, key.split('.')) ?? defaultValue;\n }\n\n /**\n * Get unique key.\n */\n find<T = any>(path: string, test: object): T | undefined {\n const values = getDeep(this._config, path.split('.'));\n if (!Array.isArray(values)) {\n return;\n }\n\n return values.find((value) => isMatch(value, test));\n }\n\n /**\n * Returns the given config property or throw if it doesn't exist.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n */\n getOrThrow<K extends ConfigKey>(key: K): Exclude<DeepIndex<ConfigProto, ParseKey<K>>, undefined> {\n const value: DeepIndex<ConfigProto, ParseKey<K>> | undefined = getDeep(this._config, key.split('.'));\n if (!value) {\n throw new Error(`Config option not present: ${key}`);\n }\n return value;\n }\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\n/* THIS FILE WILL BE LOADED BY CONTEXT REPLACEMENT PLUGIN IN BROWSER ENVS. */\n\n/* global __DXOS_CONFIG__ __CONFIG_ENVS__ __CONFIG_DEFAULTS__ __CONFIG_LOCAL__ */\n\nimport localforage from 'localforage';\n\nimport { log } from '@dxos/log';\n\nconst CONFIG_ENDPOINT = '/.well-known/dx/config';\n\nexport const Local = () => {\n return typeof __CONFIG_LOCAL__ !== 'undefined' ? __CONFIG_LOCAL__ : {};\n};\n\nexport const Dynamics = async () => {\n const { publicUrl = '', dynamic } = __DXOS_CONFIG__;\n if (!dynamic) {\n log('dynamics disabled');\n return {};\n }\n\n log('fetching config...', { publicUrl });\n return await fetch(`${publicUrl}${CONFIG_ENDPOINT}`)\n .then((res) => res.json())\n .catch((error) => {\n log.warn('Failed to fetch dynamic config.', error);\n return {};\n });\n};\n\nexport const Envs = () => {\n return typeof __CONFIG_ENVS__ !== 'undefined' ? __CONFIG_ENVS__ : {};\n};\n\nexport const Defaults = () => {\n return typeof __CONFIG_DEFAULTS__ !== 'undefined' ? __CONFIG_DEFAULTS__ : {};\n};\n\n/**\n * Settings config from browser storage.\n */\nexport const Storage = async () => {\n try {\n const config = await localforage.getItem('dxos.org/settings/config');\n if (config) {\n return config;\n }\n } catch (err) {\n log.warn('Failed to load config', { err });\n }\n return {};\n};\n\nexport const Remote = (target, authenticationToken) => {\n if (!target) {\n return {};\n }\n\n try {\n const url = new URL(target);\n const protocol = url.protocol.slice(0, -1);\n\n return {\n runtime: {\n client: {\n // TODO(burdon): Remove vault.html.\n remoteSource: url.origin + (protocol.startsWith('http') ? '/vault.html' : ''),\n remoteSourceAuthenticationToken: authenticationToken,\n },\n },\n };\n } catch (err) {\n log.catch(err);\n return {};\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\n/* THIS FILE WILL BE LOADED BY CONTEXT REPLACEMENT PLUGIN IN BROWSER ENVS. */\n\nimport localforage from 'localforage';\n\nimport { log } from '@dxos/log';\n\nlet PERFORMING_CONFIG_SAVE = false;\n\nexport const SaveConfig = async (config) => {\n if (PERFORMING_CONFIG_SAVE) {\n log.warn('Already performing config save');\n return;\n }\n PERFORMING_CONFIG_SAVE = true;\n\n try {\n await localforage.setItem('dxos.org/settings/config', config);\n } catch (err) {\n log.warn('Failed to save config', { err });\n return {};\n } finally {\n PERFORMING_CONFIG_SAVE = false;\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport const FILE_DEFAULTS = 'defaults.yml';\nexport const FILE_ENVS = 'envs-map.yml';\nexport const FILE_DYNAMICS = 'config.yml';\n\ntype DotPrefix<T extends string> = T extends '' ? '' : `.${T}`;\n\n/**\n * Returns all dot-separated nested keys for an object.\n *\n * Read more: https://stackoverflow.com/a/68404823.\n */\ntype DotNestedKeys<T> = (\n T extends object\n ? {\n [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<DotNestedKeys<T[K]>>}`;\n }[Exclude<keyof T, symbol>]\n : ''\n) extends infer D\n ? Extract<D, string>\n : never;\n\n/**\n * Parse a dot separated nested key into an array of keys.\n *\n * Example: 'services.signal.server' -> ['services', 'signal', 'server'].\n */\nexport type ParseKey<K extends string> = K extends `${infer L}.${infer Rest}` ? [L, ...ParseKey<Rest>] : [K];\n\n/**\n * Array of types that can act as an object key.\n */\ntype Keys = (keyof any)[];\n\n/**\n * Retrieves a property type in a series of nested objects.\n *\n * Read more: https://stackoverflow.com/a/61648690.\n */\nexport type DeepIndex<T, KS extends Keys, Fail = undefined> = KS extends [infer F, ...infer R]\n ? F extends keyof Exclude<T, undefined>\n ? R extends Keys\n ? DeepIndex<Exclude<T, undefined>[F], R, Fail>\n : Fail\n : Fail\n : T;\n\n/**\n * Any nested dot separated key that can be in config.\n */\n// TODO(egorgripasov): Clean once old config deprecated.\nexport type ConfigKey = DotNestedKeys<ConfigProto>;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Match from 'effect/Match';\n\nimport { Config } from './config';\n\nexport type ConfigPresetOptions = {\n /**\n * Edge service.\n * @default main\n */\n edge?: 'local' | 'dev' | 'main';\n};\n\nexport const configPreset = ({ edge = 'main' }: ConfigPresetOptions = {}) =>\n new Config({\n version: 1,\n runtime: {\n client: {\n edgeFeatures: {\n signaling: true,\n echoReplicator: true,\n feedReplicator: true,\n },\n },\n services: {\n edge: {\n url: Match.value(edge).pipe(\n Match.when('local', () => 'http://localhost:8787'),\n Match.when('dev', () => 'https://edge.dxos.workers.dev'),\n Match.when('main', () => 'https://edge-main.dxos.workers.dev'),\n Match.exhaustive,\n ),\n },\n },\n },\n });\n"],
|
|
5
|
-
"mappings": ";AAKA,YAAYA,UAAU;;;ACDtB,SAASC,eAAe;AACxB,OAAOC,kBAAkB;AACzB,OAAOC,aAAa;AAEpB,SAASC,0BAA0B;AACnC,SAASC,cAAc;AAEvB,SAASC,aAAa;AACtB,SAASC,SAASC,eAAe;;;;;;;AAKjC,IAAMC,iBAAiBC,OAAOC,gBAAgB,oBAAA;AAgBvC,IAAMC,mBAAmB,CAACC,MAAmBC,WAAAA;AAClD,QAAMC,SAAS,CAAC;AAEhB,aAAW,CAACC,KAAK,EAAEC,MAAMC,KAAI,CAAE,KAAKC,OAAOC,QAAQP,IAAAA,GAAO;AACxD,QAAIQ,SAAQP,OAAOE,GAAAA;AAEnB,QAAIK,WAAUC,QAAW;AACvB,UAAIJ,MAAM;AACR,gBAAQA,MAAAA;UACN,KAAK,WAAW;AACdG,YAAAA,SAAQE,QAAQF,MAAAA;AAChB;UACF;UAEA,KAAK,UAAU;AACbA,YAAAA,SAAQG,OAAOH,MAAAA;AACf;UACF;UAEA,KAAK,UAAU;AACb;UACF;UAEA,KAAK,QAAQ;AACXA,YAAAA,SAAQA,SAAQI,KAAKC,MAAML,MAAAA,IAAS;AACpC;UACF;UAEA,SAAS;AACP,kBAAM,IAAIM,MAAM,iBAAiBT,IAAAA,EAAM;UACzC;QACF;MACF;AAEAU,cAAQb,QAAQE,KAAKY,MAAM,GAAA,GAAMR,MAAAA;IACnC;EACF;AAEA,SAAON;AACT;AAOO,IAAMe,iBAAiB,CAACjB,MAAmBC,WAAAA;AAChD,QAAMC,SAA8B,CAAC;AAErC,aAAW,CAACC,KAAK,EAAEC,MAAMC,KAAI,CAAE,KAAKC,OAAOC,QAAQP,IAAAA,GAAO;AACxD,UAAMQ,SAAQU,QAAQjB,QAAQG,KAAKY,MAAM,GAAA,CAAA;AACzC,QAAIR,WAAUC,QAAW;AACvB,cAAQJ,MAAAA;QACN,KAAK;AACHH,iBAAOC,GAAAA,IAAOS,KAAKO,UAAUX,MAAAA;AAC7B;QACF;AACEN,iBAAOC,GAAAA,IAAOK;MAClB;IACF;EACF;AAEA,SAAON;AACT;AAKO,IAAMkB,iBAAiB,CAAClB,WAAAA;AAC7B,MAAI,EAAE,aAAaA,SAAS;AAC1B,UAAM,IAAImB,mBAAmB,
|
|
6
|
-
"names": ["defs", "boolean", "defaultsDeep", "isMatch", "InvalidConfigError", "schema", "trace", "getDeep", "setDeep", "configRootType", "schema", "getCodecForType", "mapFromKeyValues", "spec", "values", "config", "key", "path", "type", "Object", "entries", "value", "undefined", "boolean", "Number", "JSON", "parse", "Error", "setDeep", "split", "mapToKeyValues", "getDeep", "stringify", "validateConfig", "InvalidConfigError", "version", "error", "protoType", "verify", "ConfigResource", "Symbol", "for", "Config", "_config", "objects", "defaultsDeep", "get", "defaultValue", "find", "test", "Array", "isArray", "isMatch", "getOrThrow", "resource", "annotation", "localforage", "log", "FILE_DEFAULTS", "FILE_ENVS", "FILE_DYNAMICS", "Match", "configPreset", "edge", "Config", "version", "runtime", "client", "edgeFeatures", "signaling", "echoReplicator", "feedReplicator", "services", "url", "value", "pipe", "when", "exhaustive"]
|
|
3
|
+
"sources": ["../../../src/index.ts", "../../../src/config.ts", "../../../src/config-service.ts", "../../../src/loaders/browser.js", "../../../src/savers/browser.js", "../../../src/types.ts", "../../../src/preset.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\n// TODO(burdon): Why is this exported? (Rename).\nexport * as defs from '@dxos/protocols/proto/dxos/config';\n\nexport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport * from './config';\nexport * from './config-service';\nexport * from './loaders';\nexport * from './savers';\nexport * from './plugin';\nexport * from './types';\nexport * from './preset';\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { boolean } from 'boolean';\nimport defaultsDeep from 'lodash.defaultsdeep';\nimport isMatch from 'lodash.ismatch';\n\nimport { InvalidConfigError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\nimport { trace } from '@dxos/tracing';\nimport { getDeep, setDeep } from '@dxos/util';\n\nimport { type ConfigKey, type DeepIndex, type ParseKey } from './types';\n\ntype MappingSpec = Record<string, { path: string; type?: string }>;\nconst configRootType = schema.getCodecForType('dxos.config.Config');\n\n/**\n * Maps the given objects onto a flattened set of (key x values).\n *\n * Expects parsed yaml content of the form:\n *\n * ```\n * ENV_VAR:\n * path: config.selector.path\n * ```\n *\n * @param {object} spec\n * @param {object} values\n * @return {object}\n */\nexport const mapFromKeyValues = (spec: MappingSpec, values: Record<string, any>) => {\n const config = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n let value = values[key];\n\n if (value !== undefined) {\n if (type) {\n switch (type) {\n case 'boolean': {\n value = boolean(value);\n break;\n }\n\n case 'number': {\n value = Number(value);\n break;\n }\n\n case 'string': {\n break;\n }\n\n case 'json': {\n value = value ? JSON.parse(value) : null;\n break;\n }\n\n default: {\n throw new Error(`Invalid type: ${type}`);\n }\n }\n }\n\n setDeep(config, path.split('.'), value);\n }\n }\n\n return config;\n};\n\n/**\n * Maps the given flattend set of (key x values) onto a JSON object.\n * @param {object} spec\n * @param {object} values\n */\nexport const mapToKeyValues = (spec: MappingSpec, values: any) => {\n const config: Record<string, any> = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n const value = getDeep(values, path.split('.'));\n if (value !== undefined) {\n switch (type) {\n case 'json':\n config[key] = JSON.stringify(value);\n break;\n default:\n config[key] = value;\n }\n }\n }\n\n return config;\n};\n\n/**\n * Validate config object.\n */\nexport const validateConfig = (config: ConfigProto): ConfigProto => {\n if (!('version' in config)) {\n throw new InvalidConfigError({ message: 'Version not specified' });\n }\n\n if (config?.version !== 1) {\n throw new InvalidConfigError({ message: `Invalid config version: ${config.version}` });\n }\n\n const error = configRootType.protoType.verify(config);\n if (error) {\n throw new InvalidConfigError({ message: String(error) });\n }\n\n return config;\n};\n\nexport const ConfigResource = Symbol.for('dxos.resource.Config');\n\n/**\n * Global configuration object.\n * NOTE: Config objects are immutable.\n */\n@trace.resource({ annotation: ConfigResource })\nexport class Config {\n private readonly _config: any;\n\n /**\n * Creates an immutable instance.\n * @constructor\n */\n constructor(config: ConfigProto = {}, ...objects: ConfigProto[]) {\n this._config = validateConfig(defaultsDeep(config, ...objects, { version: 1 }));\n }\n\n /**\n * Returns an immutable config JSON object.\n */\n get values(): ConfigProto {\n return this._config;\n }\n\n /**\n * Returns the given config property.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n * @param defaultValue Default value to return if option is not present in the config.\n * @returns The config value or undefined if the option is not present.\n */\n get<K extends ConfigKey>(\n key: K,\n defaultValue?: DeepIndex<ConfigProto, ParseKey<K>>,\n ): DeepIndex<ConfigProto, ParseKey<K>> | undefined {\n return getDeep(this._config, key.split('.')) ?? defaultValue;\n }\n\n /**\n * Get unique key.\n */\n find<T = any>(path: string, test: object): T | undefined {\n const values = getDeep(this._config, path.split('.'));\n if (!Array.isArray(values)) {\n return;\n }\n\n return values.find((value) => isMatch(value, test));\n }\n\n /**\n * Returns the given config property or throw if it doesn't exist.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n */\n getOrThrow<K extends ConfigKey>(key: K): Exclude<DeepIndex<ConfigProto, ParseKey<K>>, undefined> {\n const value: DeepIndex<ConfigProto, ParseKey<K>> | undefined = getDeep(this._config, key.split('.'));\n if (!value) {\n throw new Error(`Config option not present: ${key}`);\n }\n return value;\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { dirname } from 'node:path';\n\nimport * as FileSystem from '@effect/platform/FileSystem';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Yaml from 'yaml';\n\nimport { DX_CONFIG, DX_DATA } from '@dxos/client-protocol';\nimport { getProfilePath } from '@dxos/client-protocol';\n\nimport { Config } from './config';\n\nexport const memoryConfig = new Config({\n runtime: {\n client: {\n edgeFeatures: {\n echoReplicator: true,\n feedReplicator: true,\n signaling: true,\n agents: true,\n },\n },\n },\n});\n\nexport const defaultConfig = new Config({\n runtime: {\n client: {\n edgeFeatures: {\n echoReplicator: true,\n feedReplicator: true,\n signaling: true,\n agents: true,\n },\n storage: {\n persistent: true,\n },\n },\n services: {\n edge: {\n url: 'wss://edge-production.dxos.workers.dev/',\n },\n iceProviders: [\n {\n urls: 'https://edge-production.dxos.workers.dev/ice',\n },\n ],\n ai: {\n server: 'https://ai-service.dxos.workers.dev',\n },\n ipfs: {\n server: 'https://api.ipfs.dxos.network/api/v0',\n gateway: 'https://gateway.ipfs.dxos.network/ipfs',\n },\n },\n },\n});\n\n// TODO(wittjosiah): Factor out.\nexport class ConfigService extends Context.Tag('ConfigService')<ConfigService, Config>() {\n static layerMemory = Layer.effect(ConfigService, Effect.succeed(memoryConfig));\n\n static load = (args: { config: Option.Option<string>; profile: string }) => {\n const defaultConfigPath = `${getProfilePath(DX_CONFIG, args.profile)}.yml`;\n return Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const configPath = Option.getOrElse(args.config, () => defaultConfigPath);\n const configContent = yield* fs.readFileString(configPath);\n const configValues = Yaml.parse(configContent);\n return ConfigService.of(new Config(configValues));\n }).pipe(\n // If the config file doesn't exist, create it.\n Effect.catchTag('SystemError', () =>\n Effect.gen(function* () {\n const configValues = defaultConfig.values;\n {\n // Isolate DX_PROFILE storages.\n configValues.runtime ??= {};\n configValues.runtime.client ??= {};\n configValues.runtime.client.storage ??= {};\n configValues.runtime.client.storage.dataRoot = getProfilePath(\n configValues.runtime.client.storage.dataRoot ?? DX_DATA,\n args.profile,\n );\n }\n\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(dirname(defaultConfigPath), { recursive: true });\n yield* fs.writeFileString(defaultConfigPath, Yaml.stringify(configValues));\n\n return ConfigService.of(new Config(configValues));\n }),\n ),\n );\n };\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\n/* THIS FILE WILL BE LOADED BY CONTEXT REPLACEMENT PLUGIN IN BROWSER ENVS. */\n\n/* global __DXOS_CONFIG__ __CONFIG_ENVS__ __CONFIG_DEFAULTS__ __CONFIG_LOCAL__ */\n\nimport localforage from 'localforage';\n\nimport { log } from '@dxos/log';\n\nconst CONFIG_ENDPOINT = '/.well-known/dx/config';\n\nexport const Local = () => {\n return typeof __CONFIG_LOCAL__ !== 'undefined' ? __CONFIG_LOCAL__ : {};\n};\n\nexport const Dynamics = async () => {\n const { publicUrl = '', dynamic } = __DXOS_CONFIG__;\n if (!dynamic) {\n log('dynamics disabled');\n return {};\n }\n\n log('fetching config...', { publicUrl });\n return await fetch(`${publicUrl}${CONFIG_ENDPOINT}`)\n .then((res) => res.json())\n .catch((error) => {\n log.warn('Failed to fetch dynamic config.', error);\n return {};\n });\n};\n\nexport const Envs = () => {\n return typeof __CONFIG_ENVS__ !== 'undefined' ? __CONFIG_ENVS__ : {};\n};\n\nexport const Defaults = () => {\n return typeof __CONFIG_DEFAULTS__ !== 'undefined' ? __CONFIG_DEFAULTS__ : {};\n};\n\n/**\n * Settings config from browser storage.\n */\nexport const Storage = async () => {\n try {\n const config = await localforage.getItem('dxos.org/settings/config');\n if (config) {\n return config;\n }\n } catch (err) {\n log.warn('Failed to load config', { err });\n }\n return {};\n};\n\nexport const Remote = (target, authenticationToken) => {\n if (!target) {\n return {};\n }\n\n try {\n const url = new URL(target);\n const protocol = url.protocol.slice(0, -1);\n\n return {\n runtime: {\n client: {\n // TODO(burdon): Remove vault.html.\n remoteSource: url.origin + (protocol.startsWith('http') ? '/vault.html' : ''),\n remoteSourceAuthenticationToken: authenticationToken,\n },\n },\n };\n } catch (err) {\n log.catch(err);\n return {};\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\n/* THIS FILE WILL BE LOADED BY CONTEXT REPLACEMENT PLUGIN IN BROWSER ENVS. */\n\nimport localforage from 'localforage';\n\nimport { log } from '@dxos/log';\n\nlet PERFORMING_CONFIG_SAVE = false;\n\nexport const SaveConfig = async (config) => {\n if (PERFORMING_CONFIG_SAVE) {\n log.warn('Already performing config save');\n return;\n }\n PERFORMING_CONFIG_SAVE = true;\n\n try {\n await localforage.setItem('dxos.org/settings/config', config);\n } catch (err) {\n log.warn('Failed to save config', { err });\n return {};\n } finally {\n PERFORMING_CONFIG_SAVE = false;\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport const FILE_DEFAULTS = 'defaults.yml';\nexport const FILE_ENVS = 'envs-map.yml';\nexport const FILE_DYNAMICS = 'config.yml';\n\ntype DotPrefix<T extends string> = T extends '' ? '' : `.${T}`;\n\n/**\n * Returns all dot-separated nested keys for an object.\n *\n * Read more: https://stackoverflow.com/a/68404823.\n */\ntype DotNestedKeys<T> = (\n T extends object\n ? {\n [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<DotNestedKeys<T[K]>>}`;\n }[Exclude<keyof T, symbol>]\n : ''\n) extends infer D\n ? Extract<D, string>\n : never;\n\n/**\n * Parse a dot separated nested key into an array of keys.\n *\n * Example: 'services.signal.server' -> ['services', 'signal', 'server'].\n */\nexport type ParseKey<K extends string> = K extends `${infer L}.${infer Rest}` ? [L, ...ParseKey<Rest>] : [K];\n\n/**\n * Array of types that can act as an object key.\n */\ntype Keys = (keyof any)[];\n\n/**\n * Retrieves a property type in a series of nested objects.\n *\n * Read more: https://stackoverflow.com/a/61648690.\n */\nexport type DeepIndex<T, KS extends Keys, Fail = undefined> = KS extends [infer F, ...infer R]\n ? F extends keyof Exclude<T, undefined>\n ? R extends Keys\n ? DeepIndex<Exclude<T, undefined>[F], R, Fail>\n : Fail\n : Fail\n : T;\n\n/**\n * Any nested dot separated key that can be in config.\n */\n// TODO(egorgripasov): Clean once old config deprecated.\nexport type ConfigKey = DotNestedKeys<ConfigProto>;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Match from 'effect/Match';\n\nimport { Config } from './config';\n\nexport type ConfigPresetOptions = {\n /**\n * Edge service.\n * @default main\n */\n edge?: 'local' | 'dev' | 'main';\n};\n\nexport const configPreset = ({ edge = 'main' }: ConfigPresetOptions = {}) =>\n new Config({\n version: 1,\n runtime: {\n client: {\n edgeFeatures: {\n signaling: true,\n echoReplicator: true,\n feedReplicator: true,\n },\n },\n services: {\n edge: {\n url: Match.value(edge).pipe(\n Match.when('local', () => 'http://localhost:8787'),\n Match.when('dev', () => 'https://edge.dxos.workers.dev'),\n Match.when('main', () => 'https://edge-main.dxos.workers.dev'),\n Match.exhaustive,\n ),\n },\n },\n },\n });\n"],
|
|
5
|
+
"mappings": ";AAKA,YAAYA,UAAU;;;ACDtB,SAASC,eAAe;AACxB,OAAOC,kBAAkB;AACzB,OAAOC,aAAa;AAEpB,SAASC,0BAA0B;AACnC,SAASC,cAAc;AAEvB,SAASC,aAAa;AACtB,SAASC,SAASC,eAAe;;;;;;;AAKjC,IAAMC,iBAAiBC,OAAOC,gBAAgB,oBAAA;AAgBvC,IAAMC,mBAAmB,CAACC,MAAmBC,WAAAA;AAClD,QAAMC,SAAS,CAAC;AAEhB,aAAW,CAACC,KAAK,EAAEC,MAAMC,KAAI,CAAE,KAAKC,OAAOC,QAAQP,IAAAA,GAAO;AACxD,QAAIQ,SAAQP,OAAOE,GAAAA;AAEnB,QAAIK,WAAUC,QAAW;AACvB,UAAIJ,MAAM;AACR,gBAAQA,MAAAA;UACN,KAAK,WAAW;AACdG,YAAAA,SAAQE,QAAQF,MAAAA;AAChB;UACF;UAEA,KAAK,UAAU;AACbA,YAAAA,SAAQG,OAAOH,MAAAA;AACf;UACF;UAEA,KAAK,UAAU;AACb;UACF;UAEA,KAAK,QAAQ;AACXA,YAAAA,SAAQA,SAAQ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K;AACZ,QAAI,MAAM,GAAG;AACb,WAAO,CAAC;AAAA,EACV;AACF;;;ACzEA,OAAOa,kBAAiB;AAExB,SAAS,OAAAC,YAAW;AAEpB,IAAI,yBAAyB;AAEtB,IAAM,aAAa,OAAO,WAAW;AAC1C,MAAI,wBAAwB;AAC1B,IAAAA,KAAI,KAAK,gCAAgC;AACzC;AAAA,EACF;AACA,2BAAyB;AAEzB,MAAI;AACF,UAAMD,aAAY,QAAQ,4BAA4B,MAAM;AAAA,EAC9D,SAAS,KAAK;AACZ,IAAAC,KAAI,KAAK,yBAAyB,EAAE,IAAI,CAAC;AACzC,WAAO,CAAC;AAAA,EACV,UAAE;AACA,6BAAyB;AAAA,EAC3B;AACF;;;ACrBO,IAAMC,gBAAgB;AACtB,IAAMC,YAAY;AAClB,IAAMC,gBAAgB;;;ACJ7B,YAAYC,WAAW;AAYhB,IAAMC,eAAe,CAAC,EAAEC,OAAO,OAAM,IAA0B,CAAC,MACrE,IAAIC,OAAO;EACTC,SAAS;EACTC,SAAS;IACPC,QAAQ;MACNC,cAAc;QACZC,WAAW;QACXC,gBAAgB;QAChBC,gBAAgB;MAClB;IACF;IACAC,UAAU;MACRT,MAAM;QACJU,KAAWC,YAAMX,IAAAA,EAAMY,KACfC,WAAK,SAAS,MAAM,uBAAA,GACpBA,WAAK,OAAO,MAAM,+BAAA,GAClBA,WAAK,QAAQ,MAAM,oCAAA,GACnBC,gBAAU;MAEpB;IACF;EACF;AACF,CAAA;",
|
|
6
|
+
"names": ["defs", "boolean", "defaultsDeep", "isMatch", "InvalidConfigError", "schema", "trace", "getDeep", "setDeep", "configRootType", "schema", "getCodecForType", "mapFromKeyValues", "spec", "values", "config", "key", "path", "type", "Object", "entries", "value", "undefined", "boolean", "Number", "JSON", "parse", "Error", "setDeep", "split", "mapToKeyValues", "getDeep", "stringify", "validateConfig", "InvalidConfigError", "message", "version", "error", "protoType", "verify", "String", "ConfigResource", "Symbol", "for", "Config", "_config", "objects", "defaultsDeep", "get", "defaultValue", "find", "test", "Array", "isArray", "isMatch", "getOrThrow", "resource", "annotation", "dirname", "FileSystem", "Context", "Effect", "Layer", "Option", "Yaml", "DX_CONFIG", "DX_DATA", "getProfilePath", "memoryConfig", "Config", "runtime", "client", "edgeFeatures", "echoReplicator", "feedReplicator", "signaling", "agents", "defaultConfig", "storage", "persistent", "services", "edge", "url", "iceProviders", "urls", "ai", "server", "ipfs", "gateway", "ConfigService", "Tag", "layerMemory", "effect", "succeed", "load", "args", "defaultConfigPath", "getProfilePath", "DX_CONFIG", "profile", "gen", "fs", "FileSystem", "configPath", "getOrElse", "config", "configContent", "readFileString", "configValues", "parse", "of", "pipe", "catchTag", "values", "dataRoot", "DX_DATA", "makeDirectory", "dirname", "recursive", "writeFileString", "stringify", "localforage", "log", "FILE_DEFAULTS", "FILE_ENVS", "FILE_DYNAMICS", "Match", "configPreset", "edge", "Config", "version", "runtime", "client", "edgeFeatures", "signaling", "echoReplicator", "feedReplicator", "services", "url", "value", "pipe", "when", "exhaustive"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/config.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/config.ts":{"bytes":16009,"imports":[{"path":"boolean","kind":"import-statement","external":true},{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"lodash.ismatch","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"@dxos/tracing","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/config-service.ts":{"bytes":11041,"imports":[{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@effect/platform/FileSystem","kind":"import-statement","external":true},{"path":"effect/Context","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Option","kind":"import-statement","external":true},{"path":"yaml","kind":"import-statement","external":true},{"path":"@dxos/client-protocol","kind":"import-statement","external":true},{"path":"@dxos/client-protocol","kind":"import-statement","external":true},{"path":"src/config.ts","kind":"import-statement","original":"./config"}],"format":"esm"},"src/loaders/browser.js":{"bytes":1868,"imports":[{"path":"localforage","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/savers/browser.js":{"bytes":613,"imports":[{"path":"localforage","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"(disabled):src/plugin":{"bytes":0,"imports":[]},"src/types.ts":{"bytes":2735,"imports":[],"format":"esm"},"src/preset.ts":{"bytes":3066,"imports":[{"path":"effect/Match","kind":"import-statement","external":true},{"path":"src/config.ts","kind":"import-statement","original":"./config"}],"format":"esm"},"src/index.ts":{"bytes":1404,"imports":[{"path":"@dxos/protocols/proto/dxos/config","kind":"import-statement","external":true},{"path":"src/config.ts","kind":"import-statement","original":"./config"},{"path":"src/config-service.ts","kind":"import-statement","original":"./config-service"},{"path":"src/loaders/browser.js","kind":"import-statement","original":"./loaders"},{"path":"src/savers/browser.js","kind":"import-statement","original":"./savers"},{"path":"(disabled):src/plugin","kind":"import-statement","original":"./plugin"},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"src/preset.ts","kind":"import-statement","original":"./preset"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":21222},"dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/protocols/proto/dxos/config","kind":"import-statement","external":true},{"path":"boolean","kind":"import-statement","external":true},{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"lodash.ismatch","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/protocols/proto","kind":"import-statement","external":true},{"path":"@dxos/tracing","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"@effect/platform/FileSystem","kind":"import-statement","external":true},{"path":"effect/Context","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Option","kind":"import-statement","external":true},{"path":"yaml","kind":"import-statement","external":true},{"path":"@dxos/client-protocol","kind":"import-statement","external":true},{"path":"@dxos/client-protocol","kind":"import-statement","external":true},{"path":"localforage","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"localforage","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"effect/Match","kind":"import-statement","external":true}],"exports":["Config","ConfigResource","ConfigService","Defaults","Dynamics","Envs","FILE_DEFAULTS","FILE_DYNAMICS","FILE_ENVS","Local","Remote","SaveConfig","Storage","configPreset","defaultConfig","defs","mapFromKeyValues","mapToKeyValues","memoryConfig","validateConfig"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":59},"src/config.ts":{"bytesInOutput":4080},"src/config-service.ts":{"bytesInOutput":2736},"src/loaders/browser.js":{"bytesInOutput":1537},"src/savers/browser.js":{"bytesInOutput":499},"src/types.ts":{"bytesInOutput":102},"src/preset.ts":{"bytesInOutput":541}},"bytes":10029}}}
|
|
@@ -68,14 +68,20 @@ var mapToKeyValues = (spec, values) => {
|
|
|
68
68
|
};
|
|
69
69
|
var validateConfig = (config) => {
|
|
70
70
|
if (!("version" in config)) {
|
|
71
|
-
throw new InvalidConfigError(
|
|
71
|
+
throw new InvalidConfigError({
|
|
72
|
+
message: "Version not specified"
|
|
73
|
+
});
|
|
72
74
|
}
|
|
73
75
|
if (config?.version !== 1) {
|
|
74
|
-
throw new InvalidConfigError(
|
|
76
|
+
throw new InvalidConfigError({
|
|
77
|
+
message: `Invalid config version: ${config.version}`
|
|
78
|
+
});
|
|
75
79
|
}
|
|
76
80
|
const error = configRootType.protoType.verify(config);
|
|
77
81
|
if (error) {
|
|
78
|
-
throw new InvalidConfigError(
|
|
82
|
+
throw new InvalidConfigError({
|
|
83
|
+
message: String(error)
|
|
84
|
+
});
|
|
79
85
|
}
|
|
80
86
|
return config;
|
|
81
87
|
};
|
|
@@ -136,10 +142,95 @@ Config = _ts_decorate([
|
|
|
136
142
|
})
|
|
137
143
|
], Config);
|
|
138
144
|
|
|
145
|
+
// src/config-service.ts
|
|
146
|
+
import { dirname } from "node:path";
|
|
147
|
+
import * as FileSystem from "@effect/platform/FileSystem";
|
|
148
|
+
import * as Context from "effect/Context";
|
|
149
|
+
import * as Effect from "effect/Effect";
|
|
150
|
+
import * as Layer from "effect/Layer";
|
|
151
|
+
import * as Option from "effect/Option";
|
|
152
|
+
import * as Yaml from "yaml";
|
|
153
|
+
import { DX_CONFIG, DX_DATA } from "@dxos/client-protocol";
|
|
154
|
+
import { getProfilePath } from "@dxos/client-protocol";
|
|
155
|
+
var memoryConfig = new Config({
|
|
156
|
+
runtime: {
|
|
157
|
+
client: {
|
|
158
|
+
edgeFeatures: {
|
|
159
|
+
echoReplicator: true,
|
|
160
|
+
feedReplicator: true,
|
|
161
|
+
signaling: true,
|
|
162
|
+
agents: true
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
var defaultConfig = new Config({
|
|
168
|
+
runtime: {
|
|
169
|
+
client: {
|
|
170
|
+
edgeFeatures: {
|
|
171
|
+
echoReplicator: true,
|
|
172
|
+
feedReplicator: true,
|
|
173
|
+
signaling: true,
|
|
174
|
+
agents: true
|
|
175
|
+
},
|
|
176
|
+
storage: {
|
|
177
|
+
persistent: true
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
services: {
|
|
181
|
+
edge: {
|
|
182
|
+
url: "wss://edge-production.dxos.workers.dev/"
|
|
183
|
+
},
|
|
184
|
+
iceProviders: [
|
|
185
|
+
{
|
|
186
|
+
urls: "https://edge-production.dxos.workers.dev/ice"
|
|
187
|
+
}
|
|
188
|
+
],
|
|
189
|
+
ai: {
|
|
190
|
+
server: "https://ai-service.dxos.workers.dev"
|
|
191
|
+
},
|
|
192
|
+
ipfs: {
|
|
193
|
+
server: "https://api.ipfs.dxos.network/api/v0",
|
|
194
|
+
gateway: "https://gateway.ipfs.dxos.network/ipfs"
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
var ConfigService = class _ConfigService extends Context.Tag("ConfigService")() {
|
|
200
|
+
static layerMemory = Layer.effect(_ConfigService, Effect.succeed(memoryConfig));
|
|
201
|
+
static load = (args) => {
|
|
202
|
+
const defaultConfigPath = `${getProfilePath(DX_CONFIG, args.profile)}.yml`;
|
|
203
|
+
return Effect.gen(function* () {
|
|
204
|
+
const fs2 = yield* FileSystem.FileSystem;
|
|
205
|
+
const configPath = Option.getOrElse(args.config, () => defaultConfigPath);
|
|
206
|
+
const configContent = yield* fs2.readFileString(configPath);
|
|
207
|
+
const configValues = Yaml.parse(configContent);
|
|
208
|
+
return _ConfigService.of(new Config(configValues));
|
|
209
|
+
}).pipe(
|
|
210
|
+
// If the config file doesn't exist, create it.
|
|
211
|
+
Effect.catchTag("SystemError", () => Effect.gen(function* () {
|
|
212
|
+
const configValues = defaultConfig.values;
|
|
213
|
+
{
|
|
214
|
+
configValues.runtime ??= {};
|
|
215
|
+
configValues.runtime.client ??= {};
|
|
216
|
+
configValues.runtime.client.storage ??= {};
|
|
217
|
+
configValues.runtime.client.storage.dataRoot = getProfilePath(configValues.runtime.client.storage.dataRoot ?? DX_DATA, args.profile);
|
|
218
|
+
}
|
|
219
|
+
const fs2 = yield* FileSystem.FileSystem;
|
|
220
|
+
yield* fs2.makeDirectory(dirname(defaultConfigPath), {
|
|
221
|
+
recursive: true
|
|
222
|
+
});
|
|
223
|
+
yield* fs2.writeFileString(defaultConfigPath, Yaml.stringify(configValues));
|
|
224
|
+
return _ConfigService.of(new Config(configValues));
|
|
225
|
+
}))
|
|
226
|
+
);
|
|
227
|
+
};
|
|
228
|
+
};
|
|
229
|
+
|
|
139
230
|
// src/loaders/index.ts
|
|
140
231
|
import fs from "node:fs";
|
|
141
232
|
import path from "node:path";
|
|
142
|
-
import
|
|
233
|
+
import { parse as parse2 } from "yaml";
|
|
143
234
|
import { log } from "@dxos/log";
|
|
144
235
|
|
|
145
236
|
// src/types.ts
|
|
@@ -152,7 +243,7 @@ var __dxlog_file = "/__w/dxos/dxos/packages/sdk/config/src/loaders/index.ts";
|
|
|
152
243
|
var DEFAULT_BASE_PATH = path.resolve(process.cwd(), "config");
|
|
153
244
|
var maybeLoadFile = (file) => {
|
|
154
245
|
try {
|
|
155
|
-
return
|
|
246
|
+
return parse2(fs.readFileSync(file, {
|
|
156
247
|
encoding: "utf8"
|
|
157
248
|
}));
|
|
158
249
|
} catch (err) {
|
|
@@ -205,8 +296,8 @@ var SaveConfig = async (_) => {
|
|
|
205
296
|
import { execSync } from "node:child_process";
|
|
206
297
|
import { readFileSync } from "node:fs";
|
|
207
298
|
import { resolve } from "node:path";
|
|
208
|
-
import yaml2 from "js-yaml";
|
|
209
299
|
import pkgUp from "pkg-up";
|
|
300
|
+
import { parse as parse3 } from "yaml";
|
|
210
301
|
import { invariant } from "@dxos/invariant";
|
|
211
302
|
import { log as log2 } from "@dxos/log";
|
|
212
303
|
import { setDeep as setDeep2 } from "@dxos/util";
|
|
@@ -232,7 +323,7 @@ var definitions = ({ configPath, envPath, devPath, mode = process.env.NODE_ENV,
|
|
|
232
323
|
});
|
|
233
324
|
let content = {};
|
|
234
325
|
try {
|
|
235
|
-
content =
|
|
326
|
+
content = parse3(readFileSync(value2, "utf-8"));
|
|
236
327
|
if (key === "__CONFIG_ENVS__") {
|
|
237
328
|
content = mapFromKeyValues(content, process.env);
|
|
238
329
|
}
|
|
@@ -332,6 +423,7 @@ var configPreset = ({ edge = "main" } = {}) => new Config({
|
|
|
332
423
|
export {
|
|
333
424
|
Config,
|
|
334
425
|
ConfigResource,
|
|
426
|
+
ConfigService,
|
|
335
427
|
Defaults,
|
|
336
428
|
Dynamics,
|
|
337
429
|
Envs,
|
|
@@ -344,10 +436,12 @@ export {
|
|
|
344
436
|
SaveConfig,
|
|
345
437
|
Storage,
|
|
346
438
|
configPreset,
|
|
439
|
+
defaultConfig,
|
|
347
440
|
definitions,
|
|
348
441
|
defs,
|
|
349
442
|
mapFromKeyValues,
|
|
350
443
|
mapToKeyValues,
|
|
444
|
+
memoryConfig,
|
|
351
445
|
validateConfig
|
|
352
446
|
};
|
|
353
447
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/index.ts", "../../../src/config.ts", "../../../src/loaders/index.ts", "../../../src/types.ts", "../../../src/savers/index.ts", "../../../src/plugin/definitions.ts", "../../../src/preset.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\n// TODO(burdon): Why is this exported? (Rename).\nexport * as defs from '@dxos/protocols/proto/dxos/config';\n\nexport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport * from './config';\nexport * from './loaders';\nexport * from './savers';\nexport * from './plugin';\nexport * from './types';\nexport * from './preset';\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { boolean } from 'boolean';\nimport defaultsDeep from 'lodash.defaultsdeep';\nimport isMatch from 'lodash.ismatch';\n\nimport { InvalidConfigError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\nimport { trace } from '@dxos/tracing';\nimport { getDeep, setDeep } from '@dxos/util';\n\nimport { type ConfigKey, type DeepIndex, type ParseKey } from './types';\n\ntype MappingSpec = Record<string, { path: string; type?: string }>;\nconst configRootType = schema.getCodecForType('dxos.config.Config');\n\n/**\n * Maps the given objects onto a flattened set of (key x values).\n *\n * Expects parsed yaml content of the form:\n *\n * ```\n * ENV_VAR:\n * path: config.selector.path\n * ```\n *\n * @param {object} spec\n * @param {object} values\n * @return {object}\n */\nexport const mapFromKeyValues = (spec: MappingSpec, values: Record<string, any>) => {\n const config = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n let value = values[key];\n\n if (value !== undefined) {\n if (type) {\n switch (type) {\n case 'boolean': {\n value = boolean(value);\n break;\n }\n\n case 'number': {\n value = Number(value);\n break;\n }\n\n case 'string': {\n break;\n }\n\n case 'json': {\n value = value ? JSON.parse(value) : null;\n break;\n }\n\n default: {\n throw new Error(`Invalid type: ${type}`);\n }\n }\n }\n\n setDeep(config, path.split('.'), value);\n }\n }\n\n return config;\n};\n\n/**\n * Maps the given flattend set of (key x values) onto a JSON object.\n * @param {object} spec\n * @param {object} values\n */\nexport const mapToKeyValues = (spec: MappingSpec, values: any) => {\n const config: Record<string, any> = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n const value = getDeep(values, path.split('.'));\n if (value !== undefined) {\n switch (type) {\n case 'json':\n config[key] = JSON.stringify(value);\n break;\n default:\n config[key] = value;\n }\n }\n }\n\n return config;\n};\n\n/**\n * Validate config object.\n */\nexport const validateConfig = (config: ConfigProto): ConfigProto => {\n if (!('version' in config)) {\n throw new InvalidConfigError('Version not specified');\n }\n\n if (config?.version !== 1) {\n throw new InvalidConfigError(`Invalid config version: ${config.version}`);\n }\n\n const error = configRootType.protoType.verify(config);\n if (error) {\n throw new InvalidConfigError(error);\n }\n\n return config;\n};\n\nexport const ConfigResource = Symbol.for('dxos.resource.Config');\n\n/**\n * Global configuration object.\n * NOTE: Config objects are immutable.\n */\n@trace.resource({ annotation: ConfigResource })\nexport class Config {\n private readonly _config: any;\n\n /**\n * Creates an immutable instance.\n * @constructor\n */\n constructor(config: ConfigProto = {}, ...objects: ConfigProto[]) {\n this._config = validateConfig(defaultsDeep(config, ...objects, { version: 1 }));\n }\n\n /**\n * Returns an immutable config JSON object.\n */\n get values(): ConfigProto {\n return this._config;\n }\n\n /**\n * Returns the given config property.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n * @param defaultValue Default value to return if option is not present in the config.\n * @returns The config value or undefined if the option is not present.\n */\n get<K extends ConfigKey>(\n key: K,\n defaultValue?: DeepIndex<ConfigProto, ParseKey<K>>,\n ): DeepIndex<ConfigProto, ParseKey<K>> | undefined {\n return getDeep(this._config, key.split('.')) ?? defaultValue;\n }\n\n /**\n * Get unique key.\n */\n find<T = any>(path: string, test: object): T | undefined {\n const values = getDeep(this._config, path.split('.'));\n if (!Array.isArray(values)) {\n return;\n }\n\n return values.find((value) => isMatch(value, test));\n }\n\n /**\n * Returns the given config property or throw if it doesn't exist.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n */\n getOrThrow<K extends ConfigKey>(key: K): Exclude<DeepIndex<ConfigProto, ParseKey<K>>, undefined> {\n const value: DeepIndex<ConfigProto, ParseKey<K>> | undefined = getDeep(this._config, key.split('.'));\n if (!value) {\n throw new Error(`Config option not present: ${key}`);\n }\n return value;\n }\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport yaml from 'js-yaml';\n\nimport { log } from '@dxos/log';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nimport { mapFromKeyValues } from '../config';\nimport { FILE_DEFAULTS, FILE_ENVS } from '../types';\n\n// TODO(burdon): Move code out of index file.\n\nconst DEFAULT_BASE_PATH = path.resolve(process.cwd(), 'config');\n\nconst maybeLoadFile = (file: string): any => {\n try {\n return yaml.load(fs.readFileSync(file, { encoding: 'utf8' }));\n } catch (err: any) {\n // Ignored.\n }\n};\n\n//\n// NOTE: Export LocalStorage and Dynamics for typescript to typecheck browser code (see ConfigPlugin).\n//\n\n/**\n * Profile\n */\nexport const Profile = (profile = 'default') => {\n const configFile = path.join(process.env.HOME ?? '~', `.config/dx/profile/${profile}.yml`);\n return maybeLoadFile(configFile) as ConfigProto;\n};\n\n/**\n * Development config.\n */\n// TODO(burdon): Rename or reconcile with Profile above?\nexport const Local = (): Partial<ConfigProto> => ({});\n\n/**\n * Provided dynamically by server.\n */\nexport const Dynamics = (): Partial<ConfigProto> => ({});\n\n/**\n * ENV variable (key/value) map.\n */\nexport const Envs = (basePath = DEFAULT_BASE_PATH): Partial<ConfigProto> => {\n const content = maybeLoadFile(path.resolve(basePath, FILE_ENVS));\n return content ? mapFromKeyValues(content, process.env) : {};\n};\n\n/**\n * JSON config.\n */\nexport const Defaults = (basePath = DEFAULT_BASE_PATH): Partial<ConfigProto> =>\n maybeLoadFile(path.resolve(basePath, FILE_DEFAULTS)) ?? {};\n\n/**\n * Load config from storage.\n */\nexport const Storage = async (): Promise<Partial<ConfigProto>> => ({});\n\nexport const Remote = (target: string | undefined, authenticationToken?: string): Partial<ConfigProto> => {\n if (!target) {\n return {};\n }\n\n try {\n const url = new URL(target);\n const protocol = url.protocol.slice(0, -1);\n return {\n runtime: {\n client: {\n // TODO(burdon): Remove vault.html.\n remoteSource: url.origin + (protocol.startsWith('http') ? '/vault.html' : ''),\n remoteSourceAuthenticationToken: authenticationToken,\n },\n },\n };\n } catch (err) {\n log.catch(err);\n return {};\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport const FILE_DEFAULTS = 'defaults.yml';\nexport const FILE_ENVS = 'envs-map.yml';\nexport const FILE_DYNAMICS = 'config.yml';\n\ntype DotPrefix<T extends string> = T extends '' ? '' : `.${T}`;\n\n/**\n * Returns all dot-separated nested keys for an object.\n *\n * Read more: https://stackoverflow.com/a/68404823.\n */\ntype DotNestedKeys<T> = (\n T extends object\n ? {\n [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<DotNestedKeys<T[K]>>}`;\n }[Exclude<keyof T, symbol>]\n : ''\n) extends infer D\n ? Extract<D, string>\n : never;\n\n/**\n * Parse a dot separated nested key into an array of keys.\n *\n * Example: 'services.signal.server' -> ['services', 'signal', 'server'].\n */\nexport type ParseKey<K extends string> = K extends `${infer L}.${infer Rest}` ? [L, ...ParseKey<Rest>] : [K];\n\n/**\n * Array of types that can act as an object key.\n */\ntype Keys = (keyof any)[];\n\n/**\n * Retrieves a property type in a series of nested objects.\n *\n * Read more: https://stackoverflow.com/a/61648690.\n */\nexport type DeepIndex<T, KS extends Keys, Fail = undefined> = KS extends [infer F, ...infer R]\n ? F extends keyof Exclude<T, undefined>\n ? R extends Keys\n ? DeepIndex<Exclude<T, undefined>[F], R, Fail>\n : Fail\n : Fail\n : T;\n\n/**\n * Any nested dot separated key that can be in config.\n */\n// TODO(egorgripasov): Clean once old config deprecated.\nexport type ConfigKey = DotNestedKeys<ConfigProto>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport const SaveConfig = async (_: ConfigProto) => {};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { execSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport yaml from 'js-yaml';\nimport pkgUp from 'pkg-up';\n\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { setDeep } from '@dxos/util';\n\nimport { mapFromKeyValues } from '../config';\n\nimport { type ConfigPluginOpts } from './types';\n\nconst CWD = process.cwd();\n\nexport const definitions = ({\n configPath,\n envPath,\n devPath,\n mode = process.env.NODE_ENV,\n publicUrl = '',\n env,\n}: ConfigPluginOpts) => {\n const KEYS_TO_FILE = {\n __CONFIG_DEFAULTS__: configPath?.length ? configPath : resolve(CWD, 'dx.yml'),\n __CONFIG_ENVS__: envPath?.length ? envPath : resolve(CWD, 'dx-env.yml'),\n } as { [key: string]: string };\n if (mode !== 'production') {\n KEYS_TO_FILE.__CONFIG_LOCAL__ = devPath ?? resolve(CWD, 'dx-local.yml');\n }\n\n return Object.entries(KEYS_TO_FILE).reduce(\n (prev, [key, value]) => {\n invariant(key);\n let content = {};\n try {\n content = yaml.load(readFileSync(value, 'utf-8')) as any;\n\n // Map environment variables to config values.\n if (key === '__CONFIG_ENVS__') {\n content = mapFromKeyValues(content, process.env);\n }\n\n if (key === '__CONFIG_DEFAULTS__') {\n // Load app environment variables into default config.\n Object.entries(process.env).forEach(([key, value]) => {\n if (key.startsWith('DX_') || env?.includes(key)) {\n setDeep(content, ['runtime', 'app', 'env', key], value);\n }\n });\n\n // Set build info automatically if available.\n try {\n const timestamp = new Date().toISOString();\n const commitHash =\n process.env.DX_COMMIT_HASH ??\n execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).replace('\\n', '');\n const packagePath = pkgUp.sync();\n const packageJson = packagePath && JSON.parse(readFileSync(packagePath, 'utf-8'));\n setDeep(content, ['runtime', 'app', 'build', 'timestamp'], timestamp);\n setDeep(content, ['runtime', 'app', 'build', 'commitHash'], commitHash);\n setDeep(content, ['runtime', 'app', 'build', 'version'], packageJson?.version);\n } catch {}\n }\n } catch (err: any) {\n if (err.message.includes('YAMLException')) {\n log.error(`Failed to parse file ${value}:`, err);\n } else {\n log(`Failed to load file ${value}:`, err);\n }\n\n if (key === '__CONFIG_DEFAULTS__') {\n // Default config is required.\n throw new Error(`Failed to load default config file from ${value}`);\n }\n }\n\n return {\n ...prev,\n [key]: content,\n };\n },\n {\n __CONFIG_DEFAULTS__: {},\n __CONFIG_ENVS__: {},\n __CONFIG_LOCAL__: {},\n __DXOS_CONFIG__: { dynamic: mode === 'production', publicUrl },\n },\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Match from 'effect/Match';\n\nimport { Config } from './config';\n\nexport type ConfigPresetOptions = {\n /**\n * Edge service.\n * @default main\n */\n edge?: 'local' | 'dev' | 'main';\n};\n\nexport const configPreset = ({ edge = 'main' }: ConfigPresetOptions = {}) =>\n new Config({\n version: 1,\n runtime: {\n client: {\n edgeFeatures: {\n signaling: true,\n echoReplicator: true,\n feedReplicator: true,\n },\n },\n services: {\n edge: {\n url: Match.value(edge).pipe(\n Match.when('local', () => 'http://localhost:8787'),\n Match.when('dev', () => 'https://edge.dxos.workers.dev'),\n Match.when('main', () => 'https://edge-main.dxos.workers.dev'),\n Match.exhaustive,\n ),\n },\n },\n },\n });\n"],
|
|
5
|
-
"mappings": ";;;AAKA,YAAYA,UAAU;;;ACDtB,SAASC,eAAe;AACxB,OAAOC,kBAAkB;AACzB,OAAOC,aAAa;AAEpB,SAASC,0BAA0B;AACnC,SAASC,cAAc;AAEvB,SAASC,aAAa;AACtB,SAASC,SAASC,eAAe;;;;;;;AAKjC,IAAMC,iBAAiBC,OAAOC,gBAAgB,oBAAA;AAgBvC,IAAMC,mBAAmB,CAACC,MAAmBC,WAAAA;AAClD,QAAMC,SAAS,CAAC;AAEhB,aAAW,CAACC,KAAK,EAAEC,MAAAA,OAAMC,KAAI,CAAE,KAAKC,OAAOC,QAAQP,IAAAA,GAAO;AACxD,QAAIQ,SAAQP,OAAOE,GAAAA;AAEnB,QAAIK,WAAUC,QAAW;AACvB,UAAIJ,MAAM;AACR,gBAAQA,MAAAA;UACN,KAAK,WAAW;AACdG,YAAAA,SAAQE,QAAQF,MAAAA;AAChB;UACF;UAEA,KAAK,UAAU;AACbA,YAAAA,SAAQG,OAAOH,MAAAA;AACf;UACF;UAEA,KAAK,UAAU;AACb;UACF;UAEA,KAAK,QAAQ;AACXA,YAAAA,SAAQA,SAAQI,KAAKC,MAAML,MAAAA,IAAS;AACpC;UACF;UAEA,SAAS;AACP,kBAAM,IAAIM,MAAM,iBAAiBT,IAAAA,EAAM;UACzC;QACF;MACF;AAEAU,cAAQb,QAAQE,MAAKY,MAAM,GAAA,GAAMR,MAAAA;IACnC;EACF;AAEA,SAAON;AACT;AAOO,IAAMe,iBAAiB,CAACjB,MAAmBC,WAAAA;AAChD,QAAMC,SAA8B,CAAC;AAErC,aAAW,CAACC,KAAK,EAAEC,MAAAA,OAAMC,KAAI,CAAE,KAAKC,OAAOC,QAAQP,IAAAA,GAAO;AACxD,UAAMQ,SAAQU,QAAQjB,QAAQG,MAAKY,MAAM,GAAA,CAAA;AACzC,QAAIR,WAAUC,QAAW;AACvB,cAAQJ,MAAAA;QACN,KAAK;AACHH,iBAAOC,GAAAA,IAAOS,KAAKO,UAAUX,MAAAA;AAC7B;QACF;AACEN,iBAAOC,GAAAA,IAAOK;MAClB;IACF;EACF;AAEA,SAAON;AACT;AAKO,IAAMkB,iBAAiB,CAAClB,WAAAA;AAC7B,MAAI,EAAE,aAAaA,SAAS;AAC1B,UAAM,IAAImB,mBAAmB,
|
|
6
|
-
"names": ["defs", "boolean", "defaultsDeep", "isMatch", "InvalidConfigError", "schema", "trace", "getDeep", "setDeep", "configRootType", "schema", "getCodecForType", "mapFromKeyValues", "spec", "values", "config", "key", "path", "type", "Object", "entries", "value", "undefined", "boolean", "Number", "JSON", "parse", "Error", "setDeep", "split", "mapToKeyValues", "getDeep", "stringify", "validateConfig", "InvalidConfigError", "version", "error", "protoType", "verify", "ConfigResource", "Symbol", "for", "Config", "_config", "objects", "defaultsDeep", "get", "defaultValue", "find", "test", "Array", "isArray", "isMatch", "getOrThrow", "resource", "annotation", "fs", "path", "
|
|
3
|
+
"sources": ["../../../src/index.ts", "../../../src/config.ts", "../../../src/config-service.ts", "../../../src/loaders/index.ts", "../../../src/types.ts", "../../../src/savers/index.ts", "../../../src/plugin/definitions.ts", "../../../src/preset.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\n// TODO(burdon): Why is this exported? (Rename).\nexport * as defs from '@dxos/protocols/proto/dxos/config';\n\nexport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport * from './config';\nexport * from './config-service';\nexport * from './loaders';\nexport * from './savers';\nexport * from './plugin';\nexport * from './types';\nexport * from './preset';\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { boolean } from 'boolean';\nimport defaultsDeep from 'lodash.defaultsdeep';\nimport isMatch from 'lodash.ismatch';\n\nimport { InvalidConfigError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\nimport { trace } from '@dxos/tracing';\nimport { getDeep, setDeep } from '@dxos/util';\n\nimport { type ConfigKey, type DeepIndex, type ParseKey } from './types';\n\ntype MappingSpec = Record<string, { path: string; type?: string }>;\nconst configRootType = schema.getCodecForType('dxos.config.Config');\n\n/**\n * Maps the given objects onto a flattened set of (key x values).\n *\n * Expects parsed yaml content of the form:\n *\n * ```\n * ENV_VAR:\n * path: config.selector.path\n * ```\n *\n * @param {object} spec\n * @param {object} values\n * @return {object}\n */\nexport const mapFromKeyValues = (spec: MappingSpec, values: Record<string, any>) => {\n const config = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n let value = values[key];\n\n if (value !== undefined) {\n if (type) {\n switch (type) {\n case 'boolean': {\n value = boolean(value);\n break;\n }\n\n case 'number': {\n value = Number(value);\n break;\n }\n\n case 'string': {\n break;\n }\n\n case 'json': {\n value = value ? JSON.parse(value) : null;\n break;\n }\n\n default: {\n throw new Error(`Invalid type: ${type}`);\n }\n }\n }\n\n setDeep(config, path.split('.'), value);\n }\n }\n\n return config;\n};\n\n/**\n * Maps the given flattend set of (key x values) onto a JSON object.\n * @param {object} spec\n * @param {object} values\n */\nexport const mapToKeyValues = (spec: MappingSpec, values: any) => {\n const config: Record<string, any> = {};\n\n for (const [key, { path, type }] of Object.entries(spec)) {\n const value = getDeep(values, path.split('.'));\n if (value !== undefined) {\n switch (type) {\n case 'json':\n config[key] = JSON.stringify(value);\n break;\n default:\n config[key] = value;\n }\n }\n }\n\n return config;\n};\n\n/**\n * Validate config object.\n */\nexport const validateConfig = (config: ConfigProto): ConfigProto => {\n if (!('version' in config)) {\n throw new InvalidConfigError({ message: 'Version not specified' });\n }\n\n if (config?.version !== 1) {\n throw new InvalidConfigError({ message: `Invalid config version: ${config.version}` });\n }\n\n const error = configRootType.protoType.verify(config);\n if (error) {\n throw new InvalidConfigError({ message: String(error) });\n }\n\n return config;\n};\n\nexport const ConfigResource = Symbol.for('dxos.resource.Config');\n\n/**\n * Global configuration object.\n * NOTE: Config objects are immutable.\n */\n@trace.resource({ annotation: ConfigResource })\nexport class Config {\n private readonly _config: any;\n\n /**\n * Creates an immutable instance.\n * @constructor\n */\n constructor(config: ConfigProto = {}, ...objects: ConfigProto[]) {\n this._config = validateConfig(defaultsDeep(config, ...objects, { version: 1 }));\n }\n\n /**\n * Returns an immutable config JSON object.\n */\n get values(): ConfigProto {\n return this._config;\n }\n\n /**\n * Returns the given config property.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n * @param defaultValue Default value to return if option is not present in the config.\n * @returns The config value or undefined if the option is not present.\n */\n get<K extends ConfigKey>(\n key: K,\n defaultValue?: DeepIndex<ConfigProto, ParseKey<K>>,\n ): DeepIndex<ConfigProto, ParseKey<K>> | undefined {\n return getDeep(this._config, key.split('.')) ?? defaultValue;\n }\n\n /**\n * Get unique key.\n */\n find<T = any>(path: string, test: object): T | undefined {\n const values = getDeep(this._config, path.split('.'));\n if (!Array.isArray(values)) {\n return;\n }\n\n return values.find((value) => isMatch(value, test));\n }\n\n /**\n * Returns the given config property or throw if it doesn't exist.\n *\n * @param key A key in the config object. Can be a nested property with keys separated by dots: 'services.signal.server'.\n */\n getOrThrow<K extends ConfigKey>(key: K): Exclude<DeepIndex<ConfigProto, ParseKey<K>>, undefined> {\n const value: DeepIndex<ConfigProto, ParseKey<K>> | undefined = getDeep(this._config, key.split('.'));\n if (!value) {\n throw new Error(`Config option not present: ${key}`);\n }\n return value;\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { dirname } from 'node:path';\n\nimport * as FileSystem from '@effect/platform/FileSystem';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Yaml from 'yaml';\n\nimport { DX_CONFIG, DX_DATA } from '@dxos/client-protocol';\nimport { getProfilePath } from '@dxos/client-protocol';\n\nimport { Config } from './config';\n\nexport const memoryConfig = new Config({\n runtime: {\n client: {\n edgeFeatures: {\n echoReplicator: true,\n feedReplicator: true,\n signaling: true,\n agents: true,\n },\n },\n },\n});\n\nexport const defaultConfig = new Config({\n runtime: {\n client: {\n edgeFeatures: {\n echoReplicator: true,\n feedReplicator: true,\n signaling: true,\n agents: true,\n },\n storage: {\n persistent: true,\n },\n },\n services: {\n edge: {\n url: 'wss://edge-production.dxos.workers.dev/',\n },\n iceProviders: [\n {\n urls: 'https://edge-production.dxos.workers.dev/ice',\n },\n ],\n ai: {\n server: 'https://ai-service.dxos.workers.dev',\n },\n ipfs: {\n server: 'https://api.ipfs.dxos.network/api/v0',\n gateway: 'https://gateway.ipfs.dxos.network/ipfs',\n },\n },\n },\n});\n\n// TODO(wittjosiah): Factor out.\nexport class ConfigService extends Context.Tag('ConfigService')<ConfigService, Config>() {\n static layerMemory = Layer.effect(ConfigService, Effect.succeed(memoryConfig));\n\n static load = (args: { config: Option.Option<string>; profile: string }) => {\n const defaultConfigPath = `${getProfilePath(DX_CONFIG, args.profile)}.yml`;\n return Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const configPath = Option.getOrElse(args.config, () => defaultConfigPath);\n const configContent = yield* fs.readFileString(configPath);\n const configValues = Yaml.parse(configContent);\n return ConfigService.of(new Config(configValues));\n }).pipe(\n // If the config file doesn't exist, create it.\n Effect.catchTag('SystemError', () =>\n Effect.gen(function* () {\n const configValues = defaultConfig.values;\n {\n // Isolate DX_PROFILE storages.\n configValues.runtime ??= {};\n configValues.runtime.client ??= {};\n configValues.runtime.client.storage ??= {};\n configValues.runtime.client.storage.dataRoot = getProfilePath(\n configValues.runtime.client.storage.dataRoot ?? DX_DATA,\n args.profile,\n );\n }\n\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(dirname(defaultConfigPath), { recursive: true });\n yield* fs.writeFileString(defaultConfigPath, Yaml.stringify(configValues));\n\n return ConfigService.of(new Config(configValues));\n }),\n ),\n );\n };\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { parse } from 'yaml';\n\nimport { log } from '@dxos/log';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nimport { mapFromKeyValues } from '../config';\nimport { FILE_DEFAULTS, FILE_ENVS } from '../types';\n\n// TODO(burdon): Move code out of index file.\n\nconst DEFAULT_BASE_PATH = path.resolve(process.cwd(), 'config');\n\nconst maybeLoadFile = (file: string): any => {\n try {\n return parse(fs.readFileSync(file, { encoding: 'utf8' }));\n } catch (err: any) {\n // Ignored.\n }\n};\n\n//\n// NOTE: Export LocalStorage and Dynamics for typescript to typecheck browser code (see ConfigPlugin).\n//\n\n/**\n * Profile\n */\nexport const Profile = (profile = 'default') => {\n const configFile = path.join(process.env.HOME ?? '~', `.config/dx/profile/${profile}.yml`);\n return maybeLoadFile(configFile) as ConfigProto;\n};\n\n/**\n * Development config.\n */\n// TODO(burdon): Rename or reconcile with Profile above?\nexport const Local = (): Partial<ConfigProto> => ({});\n\n/**\n * Provided dynamically by server.\n */\nexport const Dynamics = (): Partial<ConfigProto> => ({});\n\n/**\n * ENV variable (key/value) map.\n */\nexport const Envs = (basePath = DEFAULT_BASE_PATH): Partial<ConfigProto> => {\n const content = maybeLoadFile(path.resolve(basePath, FILE_ENVS));\n return content ? mapFromKeyValues(content, process.env) : {};\n};\n\n/**\n * JSON config.\n */\nexport const Defaults = (basePath = DEFAULT_BASE_PATH): Partial<ConfigProto> =>\n maybeLoadFile(path.resolve(basePath, FILE_DEFAULTS)) ?? {};\n\n/**\n * Load config from storage.\n */\nexport const Storage = async (): Promise<Partial<ConfigProto>> => ({});\n\nexport const Remote = (target: string | undefined, authenticationToken?: string): Partial<ConfigProto> => {\n if (!target) {\n return {};\n }\n\n try {\n const url = new URL(target);\n const protocol = url.protocol.slice(0, -1);\n return {\n runtime: {\n client: {\n // TODO(burdon): Remove vault.html.\n remoteSource: url.origin + (protocol.startsWith('http') ? '/vault.html' : ''),\n remoteSourceAuthenticationToken: authenticationToken,\n },\n },\n };\n } catch (err) {\n log.catch(err);\n return {};\n }\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport const FILE_DEFAULTS = 'defaults.yml';\nexport const FILE_ENVS = 'envs-map.yml';\nexport const FILE_DYNAMICS = 'config.yml';\n\ntype DotPrefix<T extends string> = T extends '' ? '' : `.${T}`;\n\n/**\n * Returns all dot-separated nested keys for an object.\n *\n * Read more: https://stackoverflow.com/a/68404823.\n */\ntype DotNestedKeys<T> = (\n T extends object\n ? {\n [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<DotNestedKeys<T[K]>>}`;\n }[Exclude<keyof T, symbol>]\n : ''\n) extends infer D\n ? Extract<D, string>\n : never;\n\n/**\n * Parse a dot separated nested key into an array of keys.\n *\n * Example: 'services.signal.server' -> ['services', 'signal', 'server'].\n */\nexport type ParseKey<K extends string> = K extends `${infer L}.${infer Rest}` ? [L, ...ParseKey<Rest>] : [K];\n\n/**\n * Array of types that can act as an object key.\n */\ntype Keys = (keyof any)[];\n\n/**\n * Retrieves a property type in a series of nested objects.\n *\n * Read more: https://stackoverflow.com/a/61648690.\n */\nexport type DeepIndex<T, KS extends Keys, Fail = undefined> = KS extends [infer F, ...infer R]\n ? F extends keyof Exclude<T, undefined>\n ? R extends Keys\n ? DeepIndex<Exclude<T, undefined>[F], R, Fail>\n : Fail\n : Fail\n : T;\n\n/**\n * Any nested dot separated key that can be in config.\n */\n// TODO(egorgripasov): Clean once old config deprecated.\nexport type ConfigKey = DotNestedKeys<ConfigProto>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\n\nexport const SaveConfig = async (_: ConfigProto) => {};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { execSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport pkgUp from 'pkg-up';\nimport { parse } from 'yaml';\n\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { setDeep } from '@dxos/util';\n\nimport { mapFromKeyValues } from '../config';\n\nimport { type ConfigPluginOpts } from './types';\n\nconst CWD = process.cwd();\n\nexport const definitions = ({\n configPath,\n envPath,\n devPath,\n mode = process.env.NODE_ENV,\n publicUrl = '',\n env,\n}: ConfigPluginOpts) => {\n const KEYS_TO_FILE = {\n __CONFIG_DEFAULTS__: configPath?.length ? configPath : resolve(CWD, 'dx.yml'),\n __CONFIG_ENVS__: envPath?.length ? envPath : resolve(CWD, 'dx-env.yml'),\n } as { [key: string]: string };\n if (mode !== 'production') {\n KEYS_TO_FILE.__CONFIG_LOCAL__ = devPath ?? resolve(CWD, 'dx-local.yml');\n }\n\n return Object.entries(KEYS_TO_FILE).reduce(\n (prev, [key, value]) => {\n invariant(key);\n let content = {};\n try {\n content = parse(readFileSync(value, 'utf-8')) as any;\n\n // Map environment variables to config values.\n if (key === '__CONFIG_ENVS__') {\n content = mapFromKeyValues(content, process.env);\n }\n\n if (key === '__CONFIG_DEFAULTS__') {\n // Load app environment variables into default config.\n Object.entries(process.env).forEach(([key, value]) => {\n if (key.startsWith('DX_') || env?.includes(key)) {\n setDeep(content, ['runtime', 'app', 'env', key], value);\n }\n });\n\n // Set build info automatically if available.\n try {\n const timestamp = new Date().toISOString();\n const commitHash =\n process.env.DX_COMMIT_HASH ??\n execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).replace('\\n', '');\n const packagePath = pkgUp.sync();\n const packageJson = packagePath && JSON.parse(readFileSync(packagePath, 'utf-8'));\n setDeep(content, ['runtime', 'app', 'build', 'timestamp'], timestamp);\n setDeep(content, ['runtime', 'app', 'build', 'commitHash'], commitHash);\n setDeep(content, ['runtime', 'app', 'build', 'version'], packageJson?.version);\n } catch {}\n }\n } catch (err: any) {\n if (err.message.includes('YAMLException')) {\n log.error(`Failed to parse file ${value}:`, err);\n } else {\n log(`Failed to load file ${value}:`, err);\n }\n\n if (key === '__CONFIG_DEFAULTS__') {\n // Default config is required.\n throw new Error(`Failed to load default config file from ${value}`);\n }\n }\n\n return {\n ...prev,\n [key]: content,\n };\n },\n {\n __CONFIG_DEFAULTS__: {},\n __CONFIG_ENVS__: {},\n __CONFIG_LOCAL__: {},\n __DXOS_CONFIG__: { dynamic: mode === 'production', publicUrl },\n },\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Match from 'effect/Match';\n\nimport { Config } from './config';\n\nexport type ConfigPresetOptions = {\n /**\n * Edge service.\n * @default main\n */\n edge?: 'local' | 'dev' | 'main';\n};\n\nexport const configPreset = ({ edge = 'main' }: ConfigPresetOptions = {}) =>\n new Config({\n version: 1,\n runtime: {\n client: {\n edgeFeatures: {\n signaling: true,\n echoReplicator: true,\n feedReplicator: true,\n },\n },\n services: {\n edge: {\n url: Match.value(edge).pipe(\n Match.when('local', () => 'http://localhost:8787'),\n Match.when('dev', () => 'https://edge.dxos.workers.dev'),\n Match.when('main', () => 'https://edge-main.dxos.workers.dev'),\n Match.exhaustive,\n ),\n },\n },\n },\n });\n"],
|
|
5
|
+
"mappings": ";;;AAKA,YAAYA,UAAU;;;ACDtB,SAASC,eAAe;AACxB,OAAOC,kBAAkB;AACzB,OAAOC,aAAa;AAEpB,SAASC,0BAA0B;AACnC,SAASC,cAAc;AAEvB,SAASC,aAAa;AACtB,SAASC,SAASC,eAAe;;;;;;;AAKjC,IAAMC,iBAAiBC,OAAOC,gBAAgB,oBAAA;AAgBvC,IAAMC,mBAAmB,CAACC,MAAmBC,WAAAA;AAClD,QAAMC,SAAS,CAAC;AAEhB,aAAW,CAACC,KAAK,EAAEC,MAAAA,OAAMC,KAAI,CAAE,KAAKC,OAAOC,QAAQP,IAAAA,GAAO;AACxD,QAAIQ,SAAQP,OAAOE,GAAAA;AAEnB,QAAIK,WAAUC,QAAW;AACvB,UAAIJ,MAAM;AACR,gBAAQA,MAAAA;UACN,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,CAAC,EAAEC,OAAO,OAAM,IAA0B,CAAC,MACrE,IAAIC,OAAO;EACTC,SAAS;EACTC,SAAS;IACPC,QAAQ;MACNC,cAAc;QACZC,WAAW;QACXC,gBAAgB;QAChBC,gBAAgB;MAClB;IACF;IACAC,UAAU;MACRT,MAAM;QACJU,KAAWC,YAAMX,IAAAA,EAAMY,KACfC,WAAK,SAAS,MAAM,uBAAA,GACpBA,WAAK,OAAO,MAAM,+BAAA,GAClBA,WAAK,QAAQ,MAAM,oCAAA,GACnBC,gBAAU;MAEpB;IACF;EACF;AACF,CAAA;",
|
|
6
|
+
"names": ["defs", "boolean", "defaultsDeep", "isMatch", "InvalidConfigError", "schema", "trace", "getDeep", "setDeep", "configRootType", "schema", "getCodecForType", "mapFromKeyValues", "spec", "values", "config", "key", "path", "type", "Object", "entries", "value", "undefined", "boolean", "Number", "JSON", "parse", "Error", "setDeep", "split", "mapToKeyValues", "getDeep", "stringify", "validateConfig", "InvalidConfigError", "message", "version", "error", "protoType", "verify", "String", "ConfigResource", "Symbol", "for", "Config", "_config", "objects", "defaultsDeep", "get", "defaultValue", "find", "test", "Array", "isArray", "isMatch", "getOrThrow", "resource", "annotation", "dirname", "FileSystem", "Context", "Effect", "Layer", "Option", "Yaml", "DX_CONFIG", "DX_DATA", "getProfilePath", "memoryConfig", "Config", "runtime", "client", "edgeFeatures", "echoReplicator", "feedReplicator", "signaling", "agents", "defaultConfig", "storage", "persistent", "services", "edge", "url", "iceProviders", "urls", "ai", "server", "ipfs", "gateway", "ConfigService", "Tag", "layerMemory", "effect", "succeed", "load", "args", "defaultConfigPath", "getProfilePath", "DX_CONFIG", "profile", "gen", "fs", "FileSystem", "configPath", "getOrElse", "config", "configContent", "readFileString", "configValues", "parse", "of", "pipe", "catchTag", "values", "dataRoot", "DX_DATA", "makeDirectory", "dirname", "recursive", "writeFileString", "stringify", "fs", "path", "parse", "log", "FILE_DEFAULTS", "FILE_ENVS", "FILE_DYNAMICS", "DEFAULT_BASE_PATH", "path", "resolve", "process", "cwd", "maybeLoadFile", "file", "parse", "fs", "readFileSync", "encoding", "err", "Profile", "profile", "configFile", "join", "env", "HOME", "Local", "Dynamics", "Envs", "basePath", "content", "FILE_ENVS", "mapFromKeyValues", "Defaults", "FILE_DEFAULTS", "Storage", "Remote", "target", "authenticationToken", "url", "URL", "protocol", "slice", "runtime", "client", "remoteSource", "origin", "startsWith", "remoteSourceAuthenticationToken", "log", "catch", "SaveConfig", "_", "execSync", "readFileSync", "resolve", "pkgUp", "parse", "invariant", "log", "setDeep", "CWD", "process", "cwd", "definitions", "configPath", "envPath", "devPath", "mode", "env", "NODE_ENV", "publicUrl", "KEYS_TO_FILE", "__CONFIG_DEFAULTS__", "length", "resolve", "__CONFIG_ENVS__", "__CONFIG_LOCAL__", "Object", "entries", "reduce", "prev", "key", "value", "invariant", "content", "parse", "readFileSync", "mapFromKeyValues", "forEach", "startsWith", "includes", "setDeep", "timestamp", "Date", "toISOString", "commitHash", "DX_COMMIT_HASH", "execSync", "encoding", "replace", "packagePath", "pkgUp", "sync", "packageJson", "JSON", "version", "err", "message", "log", "error", "Error", "__DXOS_CONFIG__", "dynamic", "Match", "configPreset", "edge", "Config", "version", "runtime", "client", "edgeFeatures", "signaling", "echoReplicator", "feedReplicator", "services", "url", "value", "pipe", "when", "exhaustive"]
|
|
7
7
|
}
|