document-model 6.2.3-dev.9 → 6.2.3-dev.90

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/README.md CHANGED
@@ -118,12 +118,6 @@ undo(count: number);
118
118
  redo(count: number);
119
119
  ```
120
120
 
121
- - `PRUNE`: Joins multiple operations into a single `LOAD_STATE` operation. Useful to keep operations history smaller. Operations to prune are selected by index, similar to the [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method in Arrays.
122
-
123
- ```javascript
124
- prune(start?: number, end?: number);
125
- ```
126
-
127
121
  ## Budget Statement Model
128
122
 
129
123
  A Budget statement follows the following data structure:
package/dist/index.d.ts CHANGED
@@ -1,16 +1,16 @@
1
1
  import { Action, AssertIsDocumentOfType, AssertIsStateOfType, CreateState, DocumentAction, DocumentModelAction, DocumentModelDocument, DocumentModelDocumentModelModule, DocumentModelModule, DocumentModelPHState, DocumentOperations, IsDocumentOfType, IsStateOfType, Operation, PHBaseState, PHDocument, PHDocumentHeader } from "@powerhousedao/shared/document-model";
2
+ import { DispatchOutcome, DocumentDispatch, RejectedAction } from "@powerhousedao/shared/document-model/dispatch";
2
3
  export * from "@powerhousedao/shared/document-model";
3
-
4
4
  //#region src/controller.d.ts
5
5
  type ScreamingSnakeToCamel<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Lowercase<Head>}${Capitalize<ScreamingSnakeToCamel<Tail>>}` : Lowercase<S>;
6
- type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {
6
+ export type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {
7
7
  document: PHDocument<TState>;
8
8
  };
9
- type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (event: DocumentChangeEvent<TState>) => void;
10
- type ActionMap<TAction extends Action, TReturn = void> = { [K in (TAction | DocumentAction)["type"] as ScreamingSnakeToCamel<K>]: (input: Extract<TAction | DocumentAction, {
9
+ export type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (event: DocumentChangeEvent<TState>) => void;
10
+ export type ActionMap<TAction extends Action, TReturn = void> = { [K in (TAction | DocumentAction)["type"] as ScreamingSnakeToCamel<K>]: (input: Extract<TAction | DocumentAction, {
11
11
  type: K;
12
- }>["input"]) => TReturn & ActionMap<TAction, TReturn> };
13
- declare class PHDocumentController<TState extends PHBaseState> implements PHDocument<TState> {
12
+ }>["input"]) => TReturn & ActionMap<TAction, TReturn>; };
13
+ export declare class PHDocumentController<TState extends PHBaseState> implements PHDocument<TState> {
14
14
  readonly module: DocumentModelModule<TState>;
15
15
  protected _document: PHDocument<TState>;
16
16
  private listeners;
@@ -25,11 +25,11 @@ declare class PHDocumentController<TState extends PHBaseState> implements PHDocu
25
25
  private notifyListeners;
26
26
  static forDocumentModel<TState extends PHBaseState, TAction extends Action>(module: DocumentModelModule<TState>): new (initialDocument?: PHDocument<TState>) => PHDocumentController<TState> & ActionMap<TAction, PHDocumentController<TState>>;
27
27
  }
28
- declare const DocumentModelController: new (initialDocument?: PHDocument<DocumentModelPHState> | undefined) => PHDocumentController<DocumentModelPHState> & ActionMap<DocumentModelAction, PHDocumentController<DocumentModelPHState>>;
28
+ export declare const DocumentModelController: new (initialDocument?: PHDocument<DocumentModelPHState> | undefined) => PHDocumentController<DocumentModelPHState> & ActionMap<DocumentModelAction, PHDocumentController<DocumentModelPHState>>;
29
29
  //#endregion
30
30
  //#region src/logger-types.d.ts
31
- type LoggerErrorHandler = (...data: any[]) => void;
32
- type ILogger = {
31
+ export type LoggerErrorHandler = (...data: any[]) => void;
32
+ export type ILogger = {
33
33
  level: "verbose" | "debug" | "info" | "warn" | "error";
34
34
  verbose: (message: string, ...replacements: any[]) => void;
35
35
  debug: (message: string, ...replacements: any[]) => void;
@@ -48,7 +48,7 @@ declare const LOG_LEVELS: {
48
48
  readonly warn: 3;
49
49
  readonly error: 4;
50
50
  };
51
- declare class ConsoleLogger implements ILogger {
51
+ export declare class ConsoleLogger implements ILogger {
52
52
  #private;
53
53
  errorHandler: LoggerErrorHandler;
54
54
  constructor(tags?: string[], handler?: LoggerErrorHandler);
@@ -61,21 +61,22 @@ declare class ConsoleLogger implements ILogger {
61
61
  warn: (message: string, ...replacements: any[]) => void;
62
62
  error: (message: string, ...replacements: any[]) => void;
63
63
  }
64
- declare const logger: ILogger;
65
- declare const setLogLevel: (level: ILogger["level"]) => void;
66
- declare const setErrorHandler: (handler: LoggerErrorHandler) => void;
67
- declare const childLogger: (tags: string[]) => ILogger;
64
+ export declare const logger: ILogger;
65
+ export declare const setLogLevel: (level: ILogger["level"]) => void;
66
+ export declare const setErrorHandler: (handler: LoggerErrorHandler) => void;
67
+ export declare const childLogger: (tags: string[]) => ILogger;
68
68
  //#endregion
69
69
  //#region src/module.d.ts
70
- declare const documentModelDocumentModelModule: DocumentModelDocumentModelModule;
70
+ export declare const documentModelDocumentModelModule: DocumentModelDocumentModelModule;
71
71
  //#endregion
72
72
  //#region src/state.d.ts
73
- declare const isStateOfType: IsStateOfType<DocumentModelPHState>;
74
- declare const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState>;
75
- declare const isDocumentOfType: IsDocumentOfType<DocumentModelPHState>;
76
- declare const assertIsDocumentOfType: AssertIsDocumentOfType<DocumentModelPHState>;
77
- declare const documentModelCreateState: CreateState<DocumentModelPHState>;
78
- declare function documentModelCreateDocument(state?: Partial<DocumentModelPHState>): DocumentModelDocument;
73
+ export declare const isStateOfType: IsStateOfType<DocumentModelPHState>;
74
+ export declare const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState>;
75
+ export declare const isDocumentOfType: IsDocumentOfType<DocumentModelPHState>;
76
+ export declare const assertIsDocumentOfType: AssertIsDocumentOfType<DocumentModelPHState>;
77
+ export declare const documentModelCreateState: CreateState<DocumentModelPHState>;
78
+ export declare function documentModelCreateDocument(state?: Partial<DocumentModelPHState>): DocumentModelDocument;
79
79
  //#endregion
80
- export { ActionMap, ConsoleLogger, DocumentChangeEvent, DocumentChangeListener, DocumentModelController, ILogger, LoggerErrorHandler, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, isDocumentOfType, isStateOfType, logger, setErrorHandler, setLogLevel };
80
+ export type { DispatchOutcome, DocumentDispatch, RejectedAction };
81
+ export {};
81
82
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/controller.ts","../src/logger-types.ts","../src/logger.ts","../src/module.ts","../src/state.ts"],"mappings":";;;;KAcK,qBAAA,qBACH,CAAA,4CACO,SAAA,CAAU,IAAA,IAAQ,UAAA,CAAW,qBAAA,CAAsB,IAAA,OACtD,SAAA,CAAU,CAAA;AAAA,KAEJ,mBAAA,gBAAmC,WAAA,GAAc,WAAA;EAC3D,QAAA,EAAU,UAAA,CAAW,MAAA;AAAA;AAAA,KAGX,sBAAA,gBAAsC,WAAA,GAAc,WAAA,KAC9D,KAAA,EAAO,mBAAA,CAAoB,MAAA;AAAA,KAGjB,SAAA,iBAA0B,MAAA,6BAC7B,OAAA,GAAU,cAAA,aAA2B,qBAAA,CAAsB,CAAA,KAChE,KAAA,EAAO,OAAA,CAAQ,OAAA,GAAU,cAAA;EAAkB,IAAA,EAAM,CAAA;AAAA,gBAC9C,OAAA,GAAU,SAAA,CAAU,OAAA,EAAS,OAAA;AAAA,cAGvB,oBAAA,gBACI,WAAA,aACJ,UAAA,CAAW,MAAA;EAAA,SACb,MAAA,EAAQ,mBAAA,CAAoB,MAAA;EAAA,UAC3B,SAAA,EAAW,UAAA,CAAW,MAAA;EAAA,QACxB,SAAA;cAGN,MAAA,EAAQ,mBAAA,CAAoB,MAAA,GAC5B,eAAA,GAAkB,UAAA,CAAW,MAAA;EAAA,IAkB3B,QAAA,CAAA,GAAY,UAAA,CAAW,MAAA;EAAA,IAIvB,MAAA,CAAA,GAAU,gBAAA;EAAA,IAGV,KAAA,CAAA,GAAS,MAAA;EAAA,IAGT,YA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,iBAAiB,eAAe,aAAa,gBAAgB,QAClE,QAAQ,oBAAoB,eAO1B,kBAAkB,WAAW,YAC1B,qBAAqB,UACxB,UAAU,SAAS,qBAAqB;;qBAIjC,8BAAuB,kBAAA,WAAA,sCAAA,qBAAA,wBAAA,UAAA,qBAAA,qBAAA;;;YC7GxB,yBAAyB;YAEzB;EACV;EAEA,UAAU,oBAAoB;EAC9B,QAAQ,oBAAoB;EAC5B,OAAO,oBAAoB;EAC3B,OAAO,oBAAoB;EAC3B,QAAQ,oBAAoB;EAE5B,cAAc;EAEd,QAAQ,mBAAmB;;;;cCqEvB;WACJ;WACA;WACA;WACA;WACA;;qBAGW,yBAAyB;;EAKpC,cAAc;EAEd,YAAY,iBAAiB,UAAU;MAOnC,sBAAsB;MAMtB,MAAM,oBAAoB;EAI9B,MAAM,iBAAiB;EAevB,UAAO,oBAAmB;EAa1B,QAAK,oBAAmB;EAaxB,OAAI,oBAAmB;EAavB,OAAI,oBAAmB;EAavB,QAAK,oBAAmB;;qBAeb,QAAQ;qBAGR,cAAW,OAAW;qBAItB,kBAAe,SAAa;qBAK5B,cAAW,mBAAqB;;;qBChLhC,kCAAkC;;;qBCVlC,eAAe,cAAc;qBAI7B,qBAAqB,oBAAoB;qBAMzC,kBAAkB,iBAAiB;qBAMnC,wBAAwB,uBACnC;qBAIW,0BAA0B,YAAY;wBAanC,4BACd,QAAQ,QAAQ,wBACf"}
package/dist/index.js CHANGED
@@ -105,7 +105,8 @@ const DocumentModelController = PHDocumentController.forDocumentModel(documentMo
105
105
  //#endregion
106
106
  //#region src/logger.ts
107
107
  const tokenSub = /@([a-zA-Z0-9_]+)/g;
108
- const dtf = new Intl.DateTimeFormat(void 0, {
108
+ let dtf;
109
+ const timeFormat = () => dtf ??= new Intl.DateTimeFormat(void 0, {
109
110
  hour12: false,
110
111
  hour: "2-digit",
111
112
  minute: "2-digit",
@@ -133,20 +134,17 @@ const stringify = (value, includeStack) => {
133
134
  const formatMessage = (tagString, message, replacements, includeStack) => {
134
135
  const meta = {};
135
136
  const uniqueTokens = [];
136
- let results;
137
- while ((results = tokenSub.exec(message)) !== null) {
138
- const tokenName = results[1];
139
- if (uniqueTokens.indexOf(tokenName) === -1) {
140
- uniqueTokens.push(tokenName);
141
- meta[tokenName] = replacements[uniqueTokens.length - 1];
142
- }
143
- }
144
- for (const [key, value] of Object.entries(meta)) message = message.replaceAll(`@${key}`, stringify(value, includeStack));
145
- const extras = replacements.slice(uniqueTokens.length);
137
+ for (const [, tokenName] of message.matchAll(tokenSub)) if (!uniqueTokens.includes(tokenName)) uniqueTokens.push(tokenName);
138
+ const bound = uniqueTokens.slice(0, replacements.length);
139
+ bound.forEach((tokenName, i) => {
140
+ meta[tokenName] = replacements[i];
141
+ });
142
+ message = message.replace(tokenSub, (match, tokenName) => Object.hasOwn(meta, tokenName) ? stringify(meta[tokenName], includeStack) : match);
143
+ const extras = replacements.slice(bound.length);
146
144
  if (extras.length > 0) message = `${message} ${extras.map((v) => stringify(v, includeStack)).join(" ")}`;
147
145
  if (tagString.length > 0) message = `${tagString} ${message}`;
148
146
  const now = /* @__PURE__ */ new Date();
149
- meta["timestamp"] = dtf.format(now);
147
+ meta["timestamp"] = timeFormat().format(now);
150
148
  return [message, meta];
151
149
  };
152
150
  const LOG_LEVELS = {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#tags","#tagString","#level","#includeStack"],"sources":["../src/state.ts","../src/module.ts","../src/controller.ts","../src/logger.ts"],"sourcesContent":["import type {\n AssertIsDocumentOfType,\n AssertIsStateOfType,\n CreateState,\n DocumentModelDocument,\n DocumentModelGlobalState,\n DocumentModelPHState,\n IsDocumentOfType,\n IsStateOfType,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentModelDocument,\n assertIsDocumentModelState,\n baseCreateDocument,\n defaultBaseState,\n documentModelDocumentType,\n documentModelInitialGlobalState,\n documentModelInitialLocalState,\n isDocumentModelDocument,\n isDocumentModelState,\n} from \"@powerhousedao/shared/document-model\";\n\nexport const isStateOfType: IsStateOfType<DocumentModelPHState> = (state) => {\n return isDocumentModelState(state);\n};\n\nexport const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState> = (\n state,\n) => {\n assertIsDocumentModelState(state);\n};\n\nexport const isDocumentOfType: IsDocumentOfType<DocumentModelPHState> = (\n document,\n) => {\n return isDocumentModelDocument(document);\n};\n\nexport const assertIsDocumentOfType: AssertIsDocumentOfType<\n DocumentModelPHState\n> = (document) => {\n assertIsDocumentModelDocument(document);\n};\nexport const documentModelCreateState: CreateState<DocumentModelPHState> = (\n state,\n) => {\n return {\n ...defaultBaseState(),\n global: {\n ...documentModelInitialGlobalState,\n ...((state?.global ?? {}) as DocumentModelGlobalState),\n },\n local: { ...documentModelInitialLocalState, ...(state?.local ?? {}) },\n };\n};\n\nexport function documentModelCreateDocument(\n state?: Partial<DocumentModelPHState>,\n): DocumentModelDocument {\n return baseCreateDocument(\n documentModelCreateState,\n state,\n documentModelDocumentType,\n );\n}\n","import type { DocumentModelDocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n actions,\n createState,\n defaultBaseState,\n documentModelFileExtension,\n documentModelGlobalState,\n documentModelLoadFromInput,\n documentModelReducer,\n documentModelSaveToFileHandle,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentOfType,\n assertIsStateOfType,\n documentModelCreateDocument,\n documentModelCreateState,\n isDocumentOfType,\n isStateOfType,\n} from \"./state.js\";\n\nconst utils = {\n fileExtension: documentModelFileExtension,\n createState: documentModelCreateState,\n createDocument: documentModelCreateDocument,\n loadFromInput: documentModelLoadFromInput,\n saveToFileHandle: documentModelSaveToFileHandle,\n isStateOfType,\n assertIsStateOfType,\n isDocumentOfType,\n assertIsDocumentOfType,\n};\n\nexport const documentModelDocumentModelModule: DocumentModelDocumentModelModule =\n {\n reducer: documentModelReducer,\n documentModel: createState(defaultBaseState(), documentModelGlobalState),\n actions,\n utils,\n };\n","import {\n type Action,\n type DocumentAction,\n type DocumentModelAction,\n type DocumentModelModule,\n type DocumentModelPHState,\n type DocumentOperations,\n type Operation,\n type PHBaseState,\n type PHDocument,\n type PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"./module.js\";\n\ntype ScreamingSnakeToCamel<S extends string> =\n S extends `${infer Head}_${infer Tail}`\n ? `${Lowercase<Head>}${Capitalize<ScreamingSnakeToCamel<Tail>>}`\n : Lowercase<S>;\n\nexport type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {\n document: PHDocument<TState>;\n};\n\nexport type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (\n event: DocumentChangeEvent<TState>,\n) => void;\n\nexport type ActionMap<TAction extends Action, TReturn = void> = {\n [K in (TAction | DocumentAction)[\"type\"] as ScreamingSnakeToCamel<K>]: (\n input: Extract<TAction | DocumentAction, { type: K }>[\"input\"],\n ) => TReturn & ActionMap<TAction, TReturn>;\n};\n\nexport class PHDocumentController<\n TState extends PHBaseState,\n> implements PHDocument<TState> {\n readonly module: DocumentModelModule<TState>;\n protected _document: PHDocument<TState>;\n private listeners: DocumentChangeListener<TState>[] = [];\n\n constructor(\n module: DocumentModelModule<TState>,\n initialDocument?: PHDocument<TState>,\n ) {\n this.module = module;\n this._document = initialDocument ?? module.utils.createDocument();\n\n // dynamically add action methods to the controller\n for (const actionType in this.module.actions) {\n Object.defineProperty(this, actionType, {\n value: (input: unknown) => {\n const action = this.module.actions[actionType](input);\n this._document = this.module.reducer(this._document, action);\n this.notifyListeners();\n return this;\n },\n });\n }\n }\n\n get document(): PHDocument<TState> {\n return this._document;\n }\n\n get header(): PHDocumentHeader {\n return this.document.header;\n }\n get state(): TState {\n return this.document.state;\n }\n get initialState(): TState {\n return this.document.initialState;\n }\n get operations(): DocumentOperations {\n return this.document.operations;\n }\n get clipboard(): Operation[] {\n return this.document.clipboard;\n }\n\n onChange(listener: DocumentChangeListener<TState>): () => void {\n this.listeners.push(listener);\n return () => {\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n\n private notifyListeners(): void {\n if (this.listeners.length === 0) return;\n const event: DocumentChangeEvent<TState> = { document: this._document };\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n\n static forDocumentModel<TState extends PHBaseState, TAction extends Action>(\n module: DocumentModelModule<TState>,\n ) {\n return class extends PHDocumentController<TState> {\n constructor(initialDocument?: PHDocument<TState>) {\n super(module, initialDocument);\n }\n } as unknown as new (\n initialDocument?: PHDocument<TState>,\n ) => PHDocumentController<TState> &\n ActionMap<TAction, PHDocumentController<TState>>;\n }\n}\n\nexport const DocumentModelController = PHDocumentController.forDocumentModel<\n DocumentModelPHState,\n DocumentModelAction\n>(documentModelDocumentModelModule);\n","import type { ILogger, LoggerErrorHandler } from \"./logger-types.js\";\n\nconst tokenSub = /@([a-zA-Z0-9_]+)/g;\nconst dtf = new Intl.DateTimeFormat(undefined, {\n hour12: false,\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n fractionalSecondDigits: 2,\n});\n\nconst stringify = (value: unknown, includeStack: boolean): string => {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"string\") return value;\n if (value instanceof Error) {\n const base = `${value.name}: ${value.message}`;\n return includeStack && value.stack ? `${base}\\n${value.stack}` : base;\n }\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n // Circular or otherwise non-serializable object; fall back to the\n // base tag (e.g. \"[object Object]\") without tripping no-base-to-string.\n return Object.prototype.toString.call(value);\n }\n }\n if (typeof value === \"function\") {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n const name = (value as Function).name;\n return name ? `${name}()` : \"anonymous()\";\n }\n // Remaining primitives (number, boolean, bigint, symbol) stringify cleanly.\n return String(value as number | boolean | bigint | symbol);\n};\n\nconst formatMessage = (\n tagString: string,\n message: string,\n replacements: any[],\n includeStack: boolean,\n): [string, Record<string, any>] => {\n const meta: Record<string, any> = {};\n const uniqueTokens: string[] = [];\n\n let results;\n while ((results = tokenSub.exec(message)) !== null) {\n const tokenName = results[1];\n const index = uniqueTokens.indexOf(tokenName);\n if (index === -1) {\n uniqueTokens.push(tokenName);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const replacement = replacements[uniqueTokens.length - 1];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n meta[tokenName] = replacement;\n }\n }\n\n // replace\n for (const [key, value] of Object.entries(meta)) {\n message = message.replaceAll(`@${key}`, stringify(value, includeStack));\n }\n\n // Any replacements past the unique-token count would otherwise be\n // silently dropped — append them so positional Errors still surface.\n const extras = replacements.slice(uniqueTokens.length);\n if (extras.length > 0) {\n message = `${message} ${extras.map((v) => stringify(v, includeStack)).join(\" \")}`;\n }\n\n if (tagString.length > 0) {\n message = `${tagString} ${message}`;\n }\n\n // timestamp\n const now = new Date();\n const timestamp = dtf.format(now);\n meta[\"timestamp\"] = timestamp;\n\n return [message, meta];\n};\n\nconst LOG_LEVELS = {\n verbose: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n} as const;\n\nexport class ConsoleLogger implements ILogger {\n #tags: string[];\n #tagString: string;\n #level: number = LOG_LEVELS.info;\n\n errorHandler: LoggerErrorHandler;\n\n constructor(tags?: string[], handler?: LoggerErrorHandler) {\n this.#tags = tags || [];\n this.#tagString = this.#tags.map((tag) => `[${tag}]`).join(\"\");\n\n this.errorHandler = handler ?? (() => {});\n }\n\n get level(): keyof typeof LOG_LEVELS {\n return Object.keys(LOG_LEVELS).find(\n (key) => LOG_LEVELS[key as keyof typeof LOG_LEVELS] === this.#level,\n ) as keyof typeof LOG_LEVELS;\n }\n\n set level(value: keyof typeof LOG_LEVELS) {\n this.#level = LOG_LEVELS[value];\n }\n\n child(tags: string[]): ILogger {\n const logger = new ConsoleLogger(\n [...this.#tags, ...tags],\n this.errorHandler,\n );\n logger.level = this.level;\n return logger;\n }\n\n // Errors get full stacks only at debug/verbose; at info/warn/error we\n // emit `name: message` to keep production logs readable.\n get #includeStack(): boolean {\n return this.#level <= LOG_LEVELS.debug;\n }\n\n verbose = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.verbose) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n debug = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.debug) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n info = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.info) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.info(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n warn = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.warn) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.warn(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n error = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.error) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.error(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n}\n\n// Singleton instance\nexport const logger: ILogger = new ConsoleLogger();\n\n// Global configuration\nexport const setLogLevel = (level: ILogger[\"level\"]) => {\n logger.level = level;\n};\n\nexport const setErrorHandler = (handler: LoggerErrorHandler) => {\n logger.errorHandler = handler;\n};\n\n// Backwards-compatible factory function\nexport const childLogger = (tags: string[]): ILogger => {\n return logger.child(tags);\n};\n"],"mappings":";;;AAsBA,MAAa,iBAAsD,UAAU;AAC3E,QAAO,qBAAqB,MAAM;;AAGpC,MA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AA8B;AAC3D,MAAI,MAAA,SAAe,WAAW,SAAS;GACrC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI/D,SAAS,SAAiB,GAAG,iBAA8B;AACzD,MAAI,MAAA,SAAe,WAAW,OAAO;GACnC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI/D,QAAQ,SAAiB,GAAG,iBAA8B;AACxD,MAAI,MAAA,SAAe,WAAW,MAAM;GAClC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,KAAK,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI9D,QAAQ,SAAiB,GAAG,iBAA8B;AACxD,MAAI,MAAA,SAAe,WAAW,MAAM;GAClC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,KAAK,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI9D,SAAS,SAAiB,GAAG,iBAA8B;AACzD,MAAI,MAAA,SAAe,WAAW,OAAO;GACnC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;;AAMjE,MAAa,SAAkB,IAAI,eAAe;AAGlD,MAAa,eAAe,UAA4B;AACtD,QAAO,QAAQ;;AAGjB,MAAa,mBAAmB,YAAgC;AAC9D,QAAO,eAAe;;AAIxB,MAAa,eAAe,SAA4B;AACtD,QAAO,OAAO,MAAM,KAAK"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/state.ts","../src/module.ts","../src/controller.ts","../src/logger.ts"],"sourcesContent":["import type {\n AssertIsDocumentOfType,\n AssertIsStateOfType,\n CreateState,\n DocumentModelDocument,\n DocumentModelGlobalState,\n DocumentModelPHState,\n IsDocumentOfType,\n IsStateOfType,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentModelDocument,\n assertIsDocumentModelState,\n baseCreateDocument,\n defaultBaseState,\n documentModelDocumentType,\n documentModelInitialGlobalState,\n documentModelInitialLocalState,\n isDocumentModelDocument,\n isDocumentModelState,\n} from \"@powerhousedao/shared/document-model\";\n\nexport const isStateOfType: IsStateOfType<DocumentModelPHState> = (state) => {\n return isDocumentModelState(state);\n};\n\nexport const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState> = (\n state,\n) => {\n assertIsDocumentModelState(state);\n};\n\nexport const isDocumentOfType: IsDocumentOfType<DocumentModelPHState> = (\n document,\n) => {\n return isDocumentModelDocument(document);\n};\n\nexport const assertIsDocumentOfType: AssertIsDocumentOfType<\n DocumentModelPHState\n> = (document) => {\n assertIsDocumentModelDocument(document);\n};\nexport const documentModelCreateState: CreateState<DocumentModelPHState> = (\n state,\n) => {\n return {\n ...defaultBaseState(),\n global: {\n ...documentModelInitialGlobalState,\n ...((state?.global ?? {}) as DocumentModelGlobalState),\n },\n local: { ...documentModelInitialLocalState, ...(state?.local ?? {}) },\n };\n};\n\nexport function documentModelCreateDocument(\n state?: Partial<DocumentModelPHState>,\n): DocumentModelDocument {\n return baseCreateDocument(\n documentModelCreateState,\n state,\n documentModelDocumentType,\n );\n}\n","import type { DocumentModelDocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n actions,\n createState,\n defaultBaseState,\n documentModelFileExtension,\n documentModelGlobalState,\n documentModelLoadFromInput,\n documentModelReducer,\n documentModelSaveToFileHandle,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentOfType,\n assertIsStateOfType,\n documentModelCreateDocument,\n documentModelCreateState,\n isDocumentOfType,\n isStateOfType,\n} from \"./state.js\";\n\nconst utils = {\n fileExtension: documentModelFileExtension,\n createState: documentModelCreateState,\n createDocument: documentModelCreateDocument,\n loadFromInput: documentModelLoadFromInput,\n saveToFileHandle: documentModelSaveToFileHandle,\n isStateOfType,\n assertIsStateOfType,\n isDocumentOfType,\n assertIsDocumentOfType,\n};\n\nexport const documentModelDocumentModelModule: DocumentModelDocumentModelModule =\n {\n reducer: documentModelReducer,\n documentModel: createState(defaultBaseState(), documentModelGlobalState),\n actions,\n utils,\n };\n","import {\n type Action,\n type DocumentAction,\n type DocumentModelAction,\n type DocumentModelModule,\n type DocumentModelPHState,\n type DocumentOperations,\n type Operation,\n type PHBaseState,\n type PHDocument,\n type PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"./module.js\";\n\ntype ScreamingSnakeToCamel<S extends string> =\n S extends `${infer Head}_${infer Tail}`\n ? `${Lowercase<Head>}${Capitalize<ScreamingSnakeToCamel<Tail>>}`\n : Lowercase<S>;\n\nexport type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {\n document: PHDocument<TState>;\n};\n\nexport type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (\n event: DocumentChangeEvent<TState>,\n) => void;\n\nexport type ActionMap<TAction extends Action, TReturn = void> = {\n [K in (TAction | DocumentAction)[\"type\"] as ScreamingSnakeToCamel<K>]: (\n input: Extract<TAction | DocumentAction, { type: K }>[\"input\"],\n ) => TReturn & ActionMap<TAction, TReturn>;\n};\n\nexport class PHDocumentController<\n TState extends PHBaseState,\n> implements PHDocument<TState> {\n readonly module: DocumentModelModule<TState>;\n protected _document: PHDocument<TState>;\n private listeners: DocumentChangeListener<TState>[] = [];\n\n constructor(\n module: DocumentModelModule<TState>,\n initialDocument?: PHDocument<TState>,\n ) {\n this.module = module;\n this._document = initialDocument ?? module.utils.createDocument();\n\n // dynamically add action methods to the controller\n for (const actionType in this.module.actions) {\n Object.defineProperty(this, actionType, {\n value: (input: unknown) => {\n const action = this.module.actions[actionType](input);\n this._document = this.module.reducer(this._document, action);\n this.notifyListeners();\n return this;\n },\n });\n }\n }\n\n get document(): PHDocument<TState> {\n return this._document;\n }\n\n get header(): PHDocumentHeader {\n return this.document.header;\n }\n get state(): TState {\n return this.document.state;\n }\n get initialState(): TState {\n return this.document.initialState;\n }\n get operations(): DocumentOperations {\n return this.document.operations;\n }\n get clipboard(): Operation[] {\n return this.document.clipboard;\n }\n\n onChange(listener: DocumentChangeListener<TState>): () => void {\n this.listeners.push(listener);\n return () => {\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n\n private notifyListeners(): void {\n if (this.listeners.length === 0) return;\n const event: DocumentChangeEvent<TState> = { document: this._document };\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n\n static forDocumentModel<TState extends PHBaseState, TAction extends Action>(\n module: DocumentModelModule<TState>,\n ) {\n return class extends PHDocumentController<TState> {\n constructor(initialDocument?: PHDocument<TState>) {\n super(module, initialDocument);\n }\n } as unknown as new (\n initialDocument?: PHDocument<TState>,\n ) => PHDocumentController<TState> &\n ActionMap<TAction, PHDocumentController<TState>>;\n }\n}\n\nexport const DocumentModelController = PHDocumentController.forDocumentModel<\n DocumentModelPHState,\n DocumentModelAction\n>(documentModelDocumentModelModule);\n","import type { ILogger, LoggerErrorHandler } from \"./logger-types.js\";\n\nconst tokenSub = /@([a-zA-Z0-9_]+)/g;\n// Built on first log: constructing it loads locale data, ~20 ms at boot.\nlet dtf: Intl.DateTimeFormat | undefined;\nconst timeFormat = () =>\n (dtf ??= new Intl.DateTimeFormat(undefined, {\n hour12: false,\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n fractionalSecondDigits: 2,\n }));\n\nconst stringify = (value: unknown, includeStack: boolean): string => {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"string\") return value;\n if (value instanceof Error) {\n const base = `${value.name}: ${value.message}`;\n return includeStack && value.stack ? `${base}\\n${value.stack}` : base;\n }\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n // Circular or otherwise non-serializable object; fall back to the\n // base tag (e.g. \"[object Object]\") without tripping no-base-to-string.\n return Object.prototype.toString.call(value);\n }\n }\n if (typeof value === \"function\") {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n const name = (value as Function).name;\n return name ? `${name}()` : \"anonymous()\";\n }\n // Remaining primitives (number, boolean, bigint, symbol) stringify cleanly.\n return String(value as number | boolean | bigint | symbol);\n};\n\nconst formatMessage = (\n tagString: string,\n message: string,\n replacements: any[],\n includeStack: boolean,\n): [string, Record<string, any>] => {\n const meta: Record<string, any> = {};\n const uniqueTokens: string[] = [];\n for (const [, tokenName] of message.matchAll(tokenSub)) {\n if (!uniqueTokens.includes(tokenName)) uniqueTokens.push(tokenName);\n }\n const bound = uniqueTokens.slice(0, replacements.length);\n bound.forEach((tokenName, i) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n meta[tokenName] = replacements[i];\n });\n\n // Single pass, so substituted values are never re-scanned; unbound tokens stay as written.\n message = message.replace(tokenSub, (match, tokenName: string) =>\n Object.hasOwn(meta, tokenName)\n ? stringify(meta[tokenName], includeStack)\n : match,\n );\n\n // Any replacements past the unique-token count would otherwise be\n // silently dropped — append them so positional Errors still surface.\n const extras = replacements.slice(bound.length);\n if (extras.length > 0) {\n message = `${message} ${extras.map((v) => stringify(v, includeStack)).join(\" \")}`;\n }\n\n if (tagString.length > 0) {\n message = `${tagString} ${message}`;\n }\n\n // timestamp\n const now = new Date();\n const timestamp = timeFormat().format(now);\n meta[\"timestamp\"] = timestamp;\n\n return [message, meta];\n};\n\nconst LOG_LEVELS = {\n verbose: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n} as const;\n\nexport class ConsoleLogger implements ILogger {\n #tags: string[];\n #tagString: string;\n #level: number = LOG_LEVELS.info;\n\n errorHandler: LoggerErrorHandler;\n\n constructor(tags?: string[], handler?: LoggerErrorHandler) {\n this.#tags = tags || [];\n this.#tagString = this.#tags.map((tag) => `[${tag}]`).join(\"\");\n\n this.errorHandler = handler ?? (() => {});\n }\n\n get level(): keyof typeof LOG_LEVELS {\n return Object.keys(LOG_LEVELS).find(\n (key) => LOG_LEVELS[key as keyof typeof LOG_LEVELS] === this.#level,\n ) as keyof typeof LOG_LEVELS;\n }\n\n set level(value: keyof typeof LOG_LEVELS) {\n this.#level = LOG_LEVELS[value];\n }\n\n child(tags: string[]): ILogger {\n const logger = new ConsoleLogger(\n [...this.#tags, ...tags],\n this.errorHandler,\n );\n logger.level = this.level;\n return logger;\n }\n\n // Errors get full stacks only at debug/verbose; at info/warn/error we\n // emit `name: message` to keep production logs readable.\n get #includeStack(): boolean {\n return this.#level <= LOG_LEVELS.debug;\n }\n\n verbose = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.verbose) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n debug = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.debug) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n info = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.info) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.info(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n warn = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.warn) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.warn(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n error = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.error) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.error(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n}\n\n// Singleton instance\nexport const logger: ILogger = new ConsoleLogger();\n\n// Global configuration\nexport const setLogLevel = (level: ILogger[\"level\"]) => {\n logger.level = level;\n};\n\nexport const setErrorHandler = (handler: LoggerErrorHandler) => {\n logger.errorHandler = handler;\n};\n\n// Backwards-compatible factory function\nexport const childLogger = (tags: string[]): ILogger => {\n return logger.child(tags);\n};\n"],"mappings":";;;AAsBA,MAAa,iBAAsD,UAAU;CAC3E,OAAO,qBAAqB,KAAK;AACnC;AAEA,MAAa,uBACX,UACG;CACH,2BAA2B,KAAK;AAClC;AAEA,MAAa,oBACX,aACG;CACH,OAAO,wBAAwB,QAAQ;AACzC;AAEA,MAAa,0BAER,aAAa;CAChB,8BAA8B,QAAQ;AACxC;AACA,MAAa,4BACX,UACG;CACH,OAAO;EACL,GAAG,iBAAiB;EACpB,QAAQ;GACN,GAAG;GACH,GAAK,OAAO,UAAU,CAAC;EACzB;EACA,OAAO;GAAE,GAAG;GAAgC,GAAI,OAAO,SAAS,CAAC;EAAG;CACtE;AACF;AAEA,SAAgB,4BACd,OACuB;CACvB,OAAO,mBACL,0BACA,OACA,yBACF;AACF;;;AC5CA,MAAM,QAAQ;CACZ,eAAe;CACf,aAAa;CACb,gBAAgB;CAChB,eAAe;CACf,kBAAkB;CAClB;CACA;CACA;CACA;AACF;AAEA,MAAa,mCACX;CACE,SAAS;CACT,eAAe,YAAY,iBAAiB,GAAG,wBAAwB;CACvE;CACA;AACF;;;ACLF,IAAa,uBAAb,MAAa,qBAEmB;CAC9B;CACA;CACA,YAAsD,CAAC;CAEvD,YACE,QACA,iBACA;EACA,KAAK,SAAS;EACd,KAAK,YAAY,mBAAmB,OAAO,MAAM,eAAe;EAGhE,KAAK,MAAM,cAAc,KAAK,OAAO,SACnC,OAAO,eAAe,MAAM,YAAY,EACtC,QAAQ,UAAmB;GACzB,MAAM,SAAS,KAAK,OAA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AK,UAAU,WAAW,MAAM;GAClC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,KAAK,YACL,SACA,cACA,KAAK,aACP;GAEA,QAAQ,KAAK,IAAI,KAAK,aAAa,IAAI,kBAAkB;EAC3D;CACF;CAEA,SAAS,SAAiB,GAAG,iBAA8B;EACzD,IAAI,KAAK,UAAU,WAAW,OAAO;GACnC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,KAAK,YACL,SACA,cACA,KAAK,aACP;GAEA,QAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,kBAAkB;EAC5D;CACF;AACF;AAGA,MAAa,SAAkB,IAAI,cAAc;AAGjD,MAAa,eAAe,UAA4B;CACtD,OAAO,QAAQ;AACjB;AAEA,MAAa,mBAAmB,YAAgC;CAC9D,OAAO,eAAe;AACxB;AAGA,MAAa,eAAe,SAA4B;CACtD,OAAO,OAAO,MAAM,IAAI;AAC1B"}
package/dist/mock.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  import { generateMock } from "@powerhousedao/shared/document-model/mock";
2
- export { generateMock };
2
+ export { generateMock };
3
+ export {};
package/dist/node.d.mts CHANGED
@@ -1,15 +1,14 @@
1
1
  import { MinimalBackupData, PHBaseState, PHDocument, Reducer, ReplayDocumentOptions, VersionedReplayConfig } from "@powerhousedao/shared/document-model";
2
2
  import { BinaryLike } from "node:crypto";
3
-
4
3
  //#region node.d.mts
5
- declare function writeFileNode(path: string, name: string, data: Uint8Array): Promise<string>;
6
- declare function readFileNode(path: string): NonSharedBuffer;
7
- declare function fetchFileNode(url: string): Promise<{
4
+ export declare function writeFileNode(path: string, name: string, data: Uint8Array): Promise<string>;
5
+ export declare function readFileNode(path: string): NonSharedBuffer;
6
+ export declare function fetchFileNode(url: string): Promise<{
8
7
  buffer: Buffer;
9
8
  mimeType?: string;
10
9
  }>;
11
- declare const getFileNode: (file: string) => Promise<NonSharedBuffer>;
12
- declare const hashNode: (data: BinaryLike, algorithm?: string, encoding?: "base64" | "hex", _params?: Record<string, unknown>) => string;
10
+ export declare const getFileNode: (file: string) => Promise<NonSharedBuffer>;
11
+ export declare const hashNode: (data: BinaryLike, algorithm?: string, encoding?: "base64" | "hex", _params?: Record<string, unknown>) => string;
13
12
  /**
14
13
  * Loads a document from a ZIP file.
15
14
  *
@@ -25,7 +24,7 @@ declare const hashNode: (data: BinaryLike, algorithm?: string, encoding?: "base6
25
24
  * @returns A promise that resolves to the document state after applying all the operations.
26
25
  * @throws An error if the initial state or the operations history is not found in the ZIP file.
27
26
  */
28
- declare function baseLoadFromFile<TState extends PHBaseState = PHBaseState>(path: string, reducer: Reducer<TState>, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
27
+ export declare function baseLoadFromFile<TState extends PHBaseState = PHBaseState>(path: string, reducer: Reducer<TState>, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
29
28
  /**
30
29
  * Loads a version-aware document from a ZIP file.
31
30
  *
@@ -35,13 +34,13 @@ declare function baseLoadFromFile<TState extends PHBaseState = PHBaseState>(path
35
34
  * @param options - Optional replay options.
36
35
  * @returns A promise that resolves to the document state after versioned replay.
37
36
  */
38
- declare function baseLoadFromFileVersioned<TState extends PHBaseState = PHBaseState>(path: string, config: VersionedReplayConfig, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
37
+ export declare function baseLoadFromFileVersioned<TState extends PHBaseState = PHBaseState>(path: string, config: VersionedReplayConfig, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
39
38
  /**
40
39
  * Saves a minimal document backup to a .phd file.
41
40
  * Used when the full document is not available (e.g., in onOperations handler).
42
41
  * Creates a file with minimal header and empty operations.
43
42
  */
44
- declare function baseMinimalSaveToFile(data: MinimalBackupData, path: string, extension: string): Promise<string>;
43
+ export declare function baseMinimalSaveToFile(data: MinimalBackupData, path: string, extension: string): Promise<string>;
45
44
  /**
46
45
  * Saves a document to a ZIP file.
47
46
  *
@@ -54,7 +53,7 @@ declare function baseMinimalSaveToFile(data: MinimalBackupData, path: string, ex
54
53
  * @param extension - The extension to use for the file.
55
54
  * @returns A promise that resolves to the path of the saved file.
56
55
  */
57
- declare function baseSaveToFile(document: PHDocument, path: string, extension: string, name?: string): Promise<string>;
56
+ export declare function baseSaveToFile(document: PHDocument, path: string, extension: string, name?: string): Promise<string>;
58
57
  //#endregion
59
- export { baseLoadFromFile, baseLoadFromFileVersioned, baseMinimalSaveToFile, baseSaveToFile, fetchFileNode, getFileNode, hashNode, readFileNode, writeFileNode };
58
+ export {};
60
59
  //# sourceMappingURL=node.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.mts","names":[],"sources":["../node.mts"],"mappings":";;;;iBAkBgB,aAAA,CACd,IAAA,UACA,IAAA,UACA,IAAA,EAAM,UAAA,GACL,OAAA;AAAA,iBAuBa,YAAA,CAAa,IAAA,WAAY,eAAA;AAAA,iBAIzB,aAAA,CACd,GAAA,WACC,OAAA;EAAU,MAAA,EAAQ,MAAA;EAAQ,QAAA;AAAA;AAAA,cAoBhB,WAAA,GAAe,IAAA,aAAY,OAAA,CAAA,eAAA;AAAA,cAI3B,QAAA,GACX,IAAA,EAAM,UAAA,EACN,SAAA,WACA,QAAA,qBACA,OAAA,GAAU,MAAA;;;;;;AAlCZ;;;;;AAIA;;;;;iBA8DsB,gBAAA,gBACL,WAAA,GAAc,WAAA,CAAA,CAE7B,IAAA,UACA,OAAA,EAAS,OAAA,CAAQ,MAAA,GACjB,OAAA,GAAU,qBAAA,GACT,OAAA,CAAQ,UAAA,CAAW,MAAA;;;;;;AA9CtB;;;;iBA4DsB,yBAAA,gBACL,WAAA,GAAc,WAAA,CAAA,CAE7B,IAAA,UACA,MAAA,EAAQ,qBAAA,EACR,OAAA,GAAU,qBAAA,GACT,OAAA,CAAQ,UAAA,CAAW,MAAA;;;;;AA9DtB;iBAwEsB,qBAAA,CACpB,IAAA,EAAM,iBAAA,EACN,IAAA,UACA,SAAA,WAAiB,OAAA;;;;;;;;;;;AAvCnB;;iBAiEsB,cAAA,CACpB,QAAA,EAAU,UAAA,EACV,IAAA,UACA,SAAA,UACA,IAAA,YAAa,OAAA"}
1
+ {"version":3,"file":"node.d.mts","names":[],"sources":["../node.mts"],"mappings":";;;wBAkBgB,cACd,cACA,cACA,MAAM,aACL;wBAuBa,aAAa,eAAY;wBAIzB,cACd,cACC;EAAU,QAAQ;EAAQ;;qBAoBhB,cAAW,iBAAgB,QAAA;qBAI3B,WAAQ,MACb,YAAU,oBAAA,6BAEU,UAChB;;;;;;;;;;;;;;;;wBAgCU,iBACpB,eAAe,cAAc,aAE7B,cACA,SAAS,QAAQ,SACjB,UAAU,wBACT,QAAQ,WAAW;;;;;;;;;;wBAcA,0BACpB,eAAe,cAAc,aAE7B,cACA,QAAQ,uBACR,UAAU,wBACT,QAAQ,WAAW;;;;;;wBAUA,sBACpB,MAAM,mBACN,cACA,oBAAiB;;;;;;;;;;;;;wBA0BG,eACpB,UAAU,YACV,cACA,mBACA,gBAAa"}
package/dist/node.mjs CHANGED
@@ -69,7 +69,8 @@ const hashNode = (data, algorithm = "sha1", encoding = "base64", _params) => {
69
69
  * @throws An error if the initial state or the operations history is not found in the ZIP file.
70
70
  */
71
71
  async function baseLoadFromFile(path, reducer, options) {
72
- return baseLoadFromInput(readFileNode(path), reducer, options);
72
+ const file = readFileNode(path);
73
+ return baseLoadFromInput(file, reducer, options);
73
74
  }
74
75
  /**
75
76
  * Loads a version-aware document from a ZIP file.
@@ -81,7 +82,8 @@ async function baseLoadFromFile(path, reducer, options) {
81
82
  * @returns A promise that resolves to the document state after versioned replay.
82
83
  */
83
84
  async function baseLoadFromFileVersioned(path, config, options) {
84
- return baseLoadFromInputVersioned(readFileNode(path), config, options);
85
+ const file = readFileNode(path);
86
+ return baseLoadFromInputVersioned(file, config, options);
85
87
  }
86
88
  /**
87
89
  * Saves a minimal document backup to a .phd file.
package/dist/node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","names":[],"sources":["../node.mts"],"sourcesContent":["import {\n baseLoadFromInput,\n baseLoadFromInputVersioned,\n createMinimalZip,\n createZip,\n type MinimalBackupData,\n type PHBaseState,\n type PHDocument,\n type Reducer,\n type ReplayDocumentOptions,\n type VersionedReplayConfig,\n} from \"@powerhousedao/shared/document-model\";\nimport type { BinaryLike } from \"node:crypto\";\nimport { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport https from \"node:https\";\nimport { join } from \"node:path\";\n\nexport function writeFileNode(\n path: string,\n name: string,\n data: Uint8Array,\n): Promise<string> {\n const filePath = join(path, name);\n fs.mkdirSync(path, { recursive: true });\n\n return new Promise((resolve, reject) => {\n try {\n fs.writeFile(filePath, data, {}, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve(filePath);\n }\n });\n } catch (error: unknown) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(String(error)));\n }\n }\n });\n}\n\nexport function readFileNode(path: string) {\n return fs.readFileSync(path);\n}\n\nexport function fetchFileNode(\n url: string,\n): Promise<{ buffer: Buffer; mimeType?: string }> {\n return new Promise((resolve, reject) => {\n https\n .get(url, (resp) => {\n const data: Uint8Array[] = [];\n const mimeType = resp.headers[\"content-type\"];\n resp.on(\"data\", (chunk: Uint8Array) => {\n data.push(chunk);\n });\n\n resp.on(\"end\", () => {\n resolve({ buffer: Buffer.concat(data), mimeType });\n });\n })\n .on(\"error\", (err) => {\n reject(err);\n });\n });\n}\n\nexport const getFileNode = (file: string) => {\n return Promise.resolve(readFileNode(file));\n};\n\nexport const hashNode = (\n data: BinaryLike,\n algorithm = \"sha1\",\n encoding: \"base64\" | \"hex\" = \"base64\",\n _params?: Record<string, unknown>,\n) => {\n if (![\"sha1\", \"sha256\", \"sha512\"].includes(algorithm)) {\n throw new Error(\n `Hashing algorithm not supported: \"${algorithm}\". Available: sha1, sha256, sha512`,\n );\n }\n\n if (![\"base64\", \"hex\"].includes(encoding)) {\n throw new Error(\n `Hash encoding not supported: \"${encoding}\". Available: base64, hex`,\n );\n }\n\n return createHash(algorithm).update(data).digest(encoding);\n};\n\n/**\n * Loads a document from a ZIP file.\n *\n * @remarks\n * This function reads a ZIP file and returns the document state after\n * applying all the operations. The reducer is used to apply the operations.\n *\n * @typeParam S - The type of the state object.\n * @typeParam A - The type of the actions that can be applied to the state object.\n *\n * @param path - The path to the ZIP file.\n * @param reducer - The reducer to apply the operations to the state object.\n * @returns A promise that resolves to the document state after applying all the operations.\n * @throws An error if the initial state or the operations history is not found in the ZIP file.\n */\nexport async function baseLoadFromFile<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n reducer: Reducer<TState>,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInput(file, reducer, options);\n}\n\n/**\n * Loads a version-aware document from a ZIP file.\n *\n * @typeParam TState - The type of the state object.\n * @param path - The path to the ZIP file.\n * @param config - Versioned replay config with per-version reducers and optional upgrade manifest.\n * @param options - Optional replay options.\n * @returns A promise that resolves to the document state after versioned replay.\n */\nexport async function baseLoadFromFileVersioned<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n config: VersionedReplayConfig,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInputVersioned<TState>(file, config, options);\n}\n\n/**\n * Saves a minimal document backup to a .phd file.\n * Used when the full document is not available (e.g., in onOperations handler).\n * Creates a file with minimal header and empty operations.\n */\nexport async function baseMinimalSaveToFile(\n data: MinimalBackupData,\n path: string,\n extension: string,\n) {\n const file = await createMinimalZip(data);\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n data.name.endsWith(fileExtension)\n ? data.name\n : `${data.name}${fileExtension}`,\n file,\n );\n}\n\n/**\n * Saves a document to a ZIP file.\n *\n * @remarks\n * This function creates a ZIP file containing the document's state and\n * operations. The file is saved to the specified path.\n *\n * @param document - The document to save to the file.\n * @param path - The path to save the file to.\n * @param extension - The extension to use for the file.\n * @returns A promise that resolves to the path of the saved file.\n */\nexport async function baseSaveToFile(\n document: PHDocument,\n path: string,\n extension: string,\n name?: string,\n) {\n const file = await createZip(document);\n const fileName = name ?? document.header.name;\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n fileName.endsWith(fileExtension) ? fileName : `${fileName}${fileExtension}`,\n file,\n );\n}\n"],"mappings":";;;;;;AAkBA,SAAgB,cACd,MACA,MACA,MACiB;CACjB,MAAM,WAAW,KAAK,MAAM,KAAK;AACjC,IAAG,UAAU,MAAM,EAAE,WAAW,MAAM,CAAC;AAEvC,QAAO,IAAI,SAAS,SAAS,WAAW;AACtC,MAAI;AACF,MAAG,UAAU,UAAU,MAAM,EAAE,GAAG,QAAQ;AACxC,QAAI,IACF,QAAO,IAAI;QAEX,SAAQ,SAAS;KAEnB;WACK,OAAgB;AACvB,OAAI,iBAAiB,MACnB,QAAO,MAAM;OAEb,QAAO,IAAI,MAAM,OAAO,MAAM,CAAC,CAAC;;GAGpC;;AAGJ,SAAgB,aAAa,MAAc;AACzC,QAAO,GAAG,aAAa,KAAK;;AAG9B,SAAgB,cACd,KACgD;AAChD,QAAO,IAAI,SAAS,SAAS,WAAW;AACtC,QACG,IAAI,MAAM,SAAS;GAClB,MAAM,OAAqB,EAAE;GAC7B,MAAM,WAAW,KAAK,QAAQ;AAC9B,QAAK,GAAG,SAAS,UAAsB;AACrC,SAAK,KAAK,MAAM;KAChB;AAEF,QAAK,GAAG,aAAa;AACnB,YAAQ;KAAE,QAAQ,OAAO,OAAO,KAAK;KAAE;KAAU,CAAC;KAClD;IACF,CACD,GAAG,UAAU,QAAQ;AACpB,UAAO,IAAI;IACX;GACJ;;AAGJ,MAAa,eAAe,SAAiB;AAC3C,QAAO,QAAQ,QAAQ,aAAa,KAAK,CAAC;;AAG5C,MAAa,YACX,MACA,YAAY,QACZ,WAA6B,UAC7B,YACG;AACH,KAAI,CAAC;EAAC;EAAQ;EAAU;EAAS,CAAC,SAAS,UAAU,CACnD,OAAM,IAAI,MACR,qCAAqC,UAAU,oCAChD;AAGH,KAAI,CAAC,CAAC,UAAU,MAAM,CAAC,SAAS,SAAS,CACvC,OAAM,IAAI,MACR,iCAAiC,SAAS,2BAC3C;AAGH,QAAO,WAAW,UAAU,CAAC,OAAO,KAAK,CAAC,OAAO,SAAS;;;;;;;;;;;;;;;;;AAkB5D,eAAsB,iBAGpB,MACA,SACA,SAC6B;AAE7B,QAAO,kBADM,aAAa,KAAK,EACA,SAAS,QAAQ;;;;;;;;;;;AAYlD,eAAsB,0BAGpB,MACA,QACA,SAC6B;AAE7B,QAAO,2BADM,aAAa,KAAK,EACiB,QAAQ,QAAQ;;;;;;;AAQlE,eAAsB,sBACpB,MACA,MACA,WACA;CACA,MAAM,OAAO,MAAM,iBAAiB,KAAK;CACzC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;AAExD,QAAO,cACL,MACA,KAAK,KAAK,SAAS,cAAc,GAC7B,KAAK,OACL,GAAG,KAAK,OAAO,iBACnB,KACD;;;;;;;;;;;;;;AAeH,eAAsB,eACpB,UACA,MACA,WACA,MACA;CACA,MAAM,OAAO,MAAM,UAAU,SAAS;CACtC,MAAM,WAAW,QAAQ,SAAS,OAAO;CACzC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;AAExD,QAAO,cACL,MACA,SAAS,SAAS,cAAc,GAAG,WAAW,GAAG,WAAW,iBAC5D,KACD"}
1
+ {"version":3,"file":"node.mjs","names":[],"sources":["../node.mts"],"sourcesContent":["import {\n baseLoadFromInput,\n baseLoadFromInputVersioned,\n createMinimalZip,\n createZip,\n type MinimalBackupData,\n type PHBaseState,\n type PHDocument,\n type Reducer,\n type ReplayDocumentOptions,\n type VersionedReplayConfig,\n} from \"@powerhousedao/shared/document-model\";\nimport type { BinaryLike } from \"node:crypto\";\nimport { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport https from \"node:https\";\nimport { join } from \"node:path\";\n\nexport function writeFileNode(\n path: string,\n name: string,\n data: Uint8Array,\n): Promise<string> {\n const filePath = join(path, name);\n fs.mkdirSync(path, { recursive: true });\n\n return new Promise((resolve, reject) => {\n try {\n fs.writeFile(filePath, data, {}, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve(filePath);\n }\n });\n } catch (error: unknown) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(String(error)));\n }\n }\n });\n}\n\nexport function readFileNode(path: string) {\n return fs.readFileSync(path);\n}\n\nexport function fetchFileNode(\n url: string,\n): Promise<{ buffer: Buffer; mimeType?: string }> {\n return new Promise((resolve, reject) => {\n https\n .get(url, (resp) => {\n const data: Uint8Array[] = [];\n const mimeType = resp.headers[\"content-type\"];\n resp.on(\"data\", (chunk: Uint8Array) => {\n data.push(chunk);\n });\n\n resp.on(\"end\", () => {\n resolve({ buffer: Buffer.concat(data), mimeType });\n });\n })\n .on(\"error\", (err) => {\n reject(err);\n });\n });\n}\n\nexport const getFileNode = (file: string) => {\n return Promise.resolve(readFileNode(file));\n};\n\nexport const hashNode = (\n data: BinaryLike,\n algorithm = \"sha1\",\n encoding: \"base64\" | \"hex\" = \"base64\",\n _params?: Record<string, unknown>,\n) => {\n if (![\"sha1\", \"sha256\", \"sha512\"].includes(algorithm)) {\n throw new Error(\n `Hashing algorithm not supported: \"${algorithm}\". Available: sha1, sha256, sha512`,\n );\n }\n\n if (![\"base64\", \"hex\"].includes(encoding)) {\n throw new Error(\n `Hash encoding not supported: \"${encoding}\". Available: base64, hex`,\n );\n }\n\n return createHash(algorithm).update(data).digest(encoding);\n};\n\n/**\n * Loads a document from a ZIP file.\n *\n * @remarks\n * This function reads a ZIP file and returns the document state after\n * applying all the operations. The reducer is used to apply the operations.\n *\n * @typeParam S - The type of the state object.\n * @typeParam A - The type of the actions that can be applied to the state object.\n *\n * @param path - The path to the ZIP file.\n * @param reducer - The reducer to apply the operations to the state object.\n * @returns A promise that resolves to the document state after applying all the operations.\n * @throws An error if the initial state or the operations history is not found in the ZIP file.\n */\nexport async function baseLoadFromFile<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n reducer: Reducer<TState>,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInput(file, reducer, options);\n}\n\n/**\n * Loads a version-aware document from a ZIP file.\n *\n * @typeParam TState - The type of the state object.\n * @param path - The path to the ZIP file.\n * @param config - Versioned replay config with per-version reducers and optional upgrade manifest.\n * @param options - Optional replay options.\n * @returns A promise that resolves to the document state after versioned replay.\n */\nexport async function baseLoadFromFileVersioned<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n config: VersionedReplayConfig,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInputVersioned<TState>(file, config, options);\n}\n\n/**\n * Saves a minimal document backup to a .phd file.\n * Used when the full document is not available (e.g., in onOperations handler).\n * Creates a file with minimal header and empty operations.\n */\nexport async function baseMinimalSaveToFile(\n data: MinimalBackupData,\n path: string,\n extension: string,\n) {\n const file = await createMinimalZip(data);\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n data.name.endsWith(fileExtension)\n ? data.name\n : `${data.name}${fileExtension}`,\n file,\n );\n}\n\n/**\n * Saves a document to a ZIP file.\n *\n * @remarks\n * This function creates a ZIP file containing the document's state and\n * operations. The file is saved to the specified path.\n *\n * @param document - The document to save to the file.\n * @param path - The path to save the file to.\n * @param extension - The extension to use for the file.\n * @returns A promise that resolves to the path of the saved file.\n */\nexport async function baseSaveToFile(\n document: PHDocument,\n path: string,\n extension: string,\n name?: string,\n) {\n const file = await createZip(document);\n const fileName = name ?? document.header.name;\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n fileName.endsWith(fileExtension) ? fileName : `${fileName}${fileExtension}`,\n file,\n );\n}\n"],"mappings":";;;;;;AAkBA,SAAgB,cACd,MACA,MACA,MACiB;CACjB,MAAM,WAAW,KAAK,MAAM,I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D;;;;;;;;;;;;;;;;AAiBA,eAAsB,iBAGpB,MACA,SACA,SAC6B;CAC7B,MAAM,OAAO,aAAa,IAAI;CAC9B,OAAO,kBAAkB,MAAM,SAAS,OAAO;AACjD;;;;;;;;;;AAWA,eAAsB,0BAGpB,MACA,QACA,SAC6B;CAC7B,MAAM,OAAO,aAAa,IAAI;CAC9B,OAAO,2BAAmC,MAAM,QAAQ,OAAO;AACjE;;;;;;AAOA,eAAsB,sBACpB,MACA,MACA,WACA;CACA,MAAM,OAAO,MAAM,iBAAiB,IAAI;CACxC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;CAExD,OAAO,cACL,MACA,KAAK,KAAK,SAAS,aAAa,IAC5B,KAAK,OACL,GAAG,KAAK,OAAO,iBACnB,IACF;AACF;;;;;;;;;;;;;AAcA,eAAsB,eACpB,UACA,MACA,WACA,MACA;CACA,MAAM,OAAO,MAAM,UAAU,QAAQ;CACrC,MAAM,WAAW,QAAQ,SAAS,OAAO;CACzC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;CAExD,OAAO,cACL,MACA,SAAS,SAAS,aAAa,IAAI,WAAW,GAAG,WAAW,iBAC5D,IACF;AACF"}
@@ -0,0 +1,119 @@
1
+ import { z } from "zod";
2
+ //#region src/scalars/scalar-literal.d.ts
3
+ /**
4
+ * Closed literal grammar handed to `parseLiteral`. It mirrors the GraphQL
5
+ * literal kinds the catalog supports so a declaration never needs graphql-js.
6
+ */
7
+ type ScalarLiteralNode = {
8
+ readonly kind: "string";
9
+ readonly value: string;
10
+ } | {
11
+ readonly kind: "int";
12
+ readonly value: string;
13
+ } | {
14
+ readonly kind: "float";
15
+ readonly value: string;
16
+ } | {
17
+ readonly kind: "boolean";
18
+ readonly value: boolean;
19
+ } | {
20
+ readonly kind: "null";
21
+ } | {
22
+ readonly kind: "enum";
23
+ readonly value: string;
24
+ } | {
25
+ readonly kind: "list";
26
+ readonly values: readonly ScalarLiteralNode[];
27
+ } | {
28
+ readonly kind: "object";
29
+ readonly fields: readonly {
30
+ readonly name: string;
31
+ readonly value: ScalarLiteralNode;
32
+ }[];
33
+ } | {
34
+ readonly kind: "variable";
35
+ readonly name: string;
36
+ };
37
+ //#endregion
38
+ //#region src/scalars/types.d.ts
39
+ declare const SCALAR_DEFINITION: unique symbol;
40
+ export declare const SCALAR_DEFINITION_VERSION = 1;
41
+ /** The wire shape of a scalar's values. */
42
+ type ScalarRepresentation = "string" | "number" | "boolean" | "json-object" | "json" | "opaque";
43
+ /** The GraphQL coercion of a scalar: variables, inline literals, and output. */
44
+ type ScalarCoercion<TValue> = {
45
+ readonly parseValue: (input: unknown) => TValue;
46
+ readonly parseLiteral: (node: ScalarLiteralNode) => TValue;
47
+ readonly serialize: (value: unknown) => unknown;
48
+ };
49
+ type ScalarDefinition<TName extends string = string, TValue = unknown> = {
50
+ readonly [SCALAR_DEFINITION]: typeof SCALAR_DEFINITION_VERSION;
51
+ readonly name: TName;
52
+ readonly description?: string;
53
+ readonly schema: z.ZodType<TValue>;
54
+ readonly typescriptType: string | null;
55
+ readonly zodSource: string | null;
56
+ readonly example?: TValue;
57
+ /**
58
+ * The wire shape of a value. It picks the literal kinds a derived coercion
59
+ * accepts. A definition from a release before this field lacks it.
60
+ */
61
+ readonly representation?: ScalarRepresentation;
62
+ /** Absent means derived: `schema` runs on every path and only the literal kinds of `representation` parse. */
63
+ readonly coercion?: ScalarCoercion<TValue>;
64
+ };
65
+ /** A definition this release made, with its representation filled. */
66
+ type DescribedScalarDefinition<TName extends string = string, TValue = unknown> = ScalarDefinition<TName, TValue> & {
67
+ readonly representation: ScalarRepresentation;
68
+ };
69
+ type ScalarValue<T> = T extends ScalarDefinition<string, infer V> ? V : never;
70
+ /** The definition format version `value` is branded with, if it has a brand. */
71
+ export declare function scalarDefinitionVersion(value: unknown): unknown;
72
+ export declare function isScalarDefinition(value: unknown): value is ScalarDefinition;
73
+ //#endregion
74
+ //#region src/scalars/catalog.d.ts
75
+ export declare const scalarCatalog: readonly DescribedScalarDefinition[];
76
+ export declare function getCatalogScalar(name: string): DescribedScalarDefinition | undefined;
77
+ type DocumentModelScalar = DescribedScalarDefinition & {
78
+ readonly typescriptType: string;
79
+ readonly zodSource: string;
80
+ };
81
+ export declare const documentModelScalars: readonly DocumentModelScalar[];
82
+ //#endregion
83
+ //#region src/scalars/representation.d.ts
84
+ type JsonRepresentation = Exclude<ScalarRepresentation, "opaque">;
85
+ //#endregion
86
+ //#region src/scalars/define-scalar.d.ts
87
+ type Json = string | number | boolean | null | Json[] | {
88
+ [key: string]: Json;
89
+ };
90
+ type OutputIsAny = {
91
+ "defineScalar refuses this schema: its output is any": never;
92
+ };
93
+ type AcceptsMissingValue = {
94
+ "defineScalar refuses this schema: it accepts a missing value; nullability belongs in the SDL": never;
95
+ };
96
+ type OutputCanBeNull = {
97
+ "defineScalar refuses this schema: its output can be null; nullability belongs in the SDL": never;
98
+ };
99
+ type OutputIsNotJson = {
100
+ "defineScalar refuses this schema: its output must be JSON": never;
101
+ };
102
+ type OutputFailsSchema = {
103
+ "defineScalar refuses this schema: its output must pass the schema again": never;
104
+ };
105
+ type TakesMissingValue<S extends z.ZodType> = S["_zod"]["optin"] extends "defaulted" ? true : S["_zod"]["optout"] extends "optional" ? true : unknown extends z.input<S> ? false : undefined extends z.input<S> ? true : false;
106
+ type CanonicalSchema<S extends z.ZodType> = 0 extends 1 & z.output<S> ? OutputIsAny : TakesMissingValue<S> extends true ? AcceptsMissingValue : z.output<S> extends Json ? null extends z.output<S> ? OutputCanBeNull : z.output<S> extends z.input<S> ? S : OutputFailsSchema : OutputIsNotJson;
107
+ type ScalarInput<TName extends string, S extends z.ZodType> = {
108
+ name: TName;
109
+ schema: S & CanonicalSchema<S>;
110
+ description?: string;
111
+ example?: NoInfer<z.input<S>>;
112
+ /** Only for a schema whose JSON shape zod cannot state, such as `z.custom`. */
113
+ representation?: JsonRepresentation;
114
+ };
115
+ export declare function defineScalar<TName extends string, S extends z.ZodType>(input: ScalarInput<TName, S>): DescribedScalarDefinition<TName, z.output<S>>;
116
+ //#endregion
117
+ export type { DescribedScalarDefinition, ScalarCoercion, ScalarDefinition, ScalarLiteralNode, ScalarRepresentation, ScalarValue };
118
+ export {};
119
+ //# sourceMappingURL=scalars.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scalars.d.ts","names":[],"sources":["../src/scalars/scalar-literal.ts","../src/scalars/types.ts","../src/scalars/catalog.ts","../src/scalars/representation.ts","../src/scalars/define-scalar.ts"],"mappings":";;;;;;KAIY;WACG;WAAyB;;WACzB;WAAsB;;WACtB;WAAwB;;WACxB;WAA0B;;WAC1B;;WACA;WAAuB;;WACvB;WAAuB,iBAAiB;;WAExC;WACA;aACE;aACA,OAAO;;;WAGT;WAA2B;;;;cChB7B;qBACA;;KAGD;;KASA,eAAe;WAChB,aAAa,mBAAmB;WAChC,eAAe,MAAM,sBAAsB;WAC3C,YAAY;;KAGX,iBACV,+BACA;YAEU,2BAA2B;WAC5B,MAAM;WACN;WACA,QAAQ,EAAE,QAAQ;WAClB;WACA;WACA,UAAU;;;;;WAKV,iBAAiB;;WAEjB,WAAW,eAAe;;;KAIzB,0BACV,+BACA,oBACE,iBAAiB,OAAO;WACjB,gBAAgB;;KAGf,YAAY,KACtB,UAAU,+BAA+B,KAAK;;wBAGhC,wBAAwB;wBAQxB,mBAAmB,iBAAiB,SAAS;;;qBCbhD,wBAAwB;wBAOrB,iBACd,eACC;KAIE,sBAAsB;WAChB;WACA;;qBAKE,+BAA+B;;;KChEhC,qBAAqB,QAAQ;;;KCIpC,0CAA0C;GAAY,cAAc;;KAEpE;EACH;;KAEG;EACH;;KAEG;EACH;;KAEG;EACH;;KAEG;EACH;;KAMG,kBAAkB,UAAU,EAAE,WACjC,gDAEI,gEAEkB,EAAE,MAAM,+BAEJ,EAAE,MAAM;KAI/B,gBAAgB,UAAU,EAAE,yBAAyB,EAAE,OAAO,KAC/D,cACA,kBAAkB,kBAChB,sBACA,EAAE,OAAO,WAAW,oBACL,EAAE,OAAO,KACpB,kBACA,EAAE,OAAO,WAAW,EAAE,MAAM,KAC1B,IACA,oBACJ;KAEH,YAAY,sBAAsB,UAAU,EAAE;EACjD,MAAM;EACN,QAAQ,IAAI,gBAAgB;EAC5B;EACA,UAAU,QAAQ,EAAE,MAAM;;EAE1B,iBAAiB;;wBAwDH,aAAa,sBAAsB,UAAU,EAAE,SAC7D,OAAO,YAAY,OAAO,KACzB,0BAA0B,OAAO,EAAE,OAAO"}
@@ -0,0 +1,499 @@
1
+ import { z } from "zod";
2
+ //#region src/scalars/types.ts
3
+ const SCALAR_DEFINITION = Symbol.for("powerhouse.scalar-definition");
4
+ const SCALAR_DEFINITION_VERSION = 1;
5
+ /** The definition format version `value` is branded with, if it has a brand. */
6
+ function scalarDefinitionVersion(value) {
7
+ return typeof value === "object" && value !== null && SCALAR_DEFINITION in value ? value[SCALAR_DEFINITION] : void 0;
8
+ }
9
+ function isScalarDefinition(value) {
10
+ return scalarDefinitionVersion(value) === 1;
11
+ }
12
+ //#endregion
13
+ //#region src/scalars/define-catalog-scalar.ts
14
+ function defineCatalogScalar(input) {
15
+ return Object.freeze({
16
+ ...input,
17
+ [SCALAR_DEFINITION]: 1
18
+ });
19
+ }
20
+ //#endregion
21
+ //#region src/scalars/scalar-literal.ts
22
+ var ScalarLiteralVariableError = class extends TypeError {
23
+ constructor(name) {
24
+ super(`Variable $${name} cannot appear inside a scalar literal; GraphQL resolves variables before literal coercion.`);
25
+ this.name = "ScalarLiteralVariableError";
26
+ }
27
+ };
28
+ /** Converts a literal node to its runtime value. A variable anywhere throws. */
29
+ function scalarLiteralValue(node) {
30
+ switch (node.kind) {
31
+ case "string":
32
+ case "enum": return node.value;
33
+ case "int":
34
+ case "float": return Number(node.value);
35
+ case "boolean": return node.value;
36
+ case "null": return null;
37
+ case "list": return node.values.map(scalarLiteralValue);
38
+ case "object": return Object.fromEntries(node.fields.map((field) => [field.name, scalarLiteralValue(field.value)]));
39
+ case "variable": throw new ScalarLiteralVariableError(node.name);
40
+ }
41
+ }
42
+ function objectFields(node) {
43
+ if (node.kind !== "object") throw new TypeError("Value must be an object literal.");
44
+ return new Map(node.fields.map((field) => [field.name, field.value]));
45
+ }
46
+ function literalString(node, field) {
47
+ if (node?.kind !== "string") throw new TypeError(`${field} must be a string literal.`);
48
+ return node.value;
49
+ }
50
+ function floatOnlyNumber(node, field) {
51
+ if (node?.kind !== "float") throw new TypeError(`${field} must be a float literal.`);
52
+ return Number.parseFloat(node.value);
53
+ }
54
+ //#endregion
55
+ //#region src/scalars/declarations/unknown.ts
56
+ const unknownScalar = defineCatalogScalar({
57
+ name: "Unknown",
58
+ typescriptType: "unknown",
59
+ zodSource: "z.unknown()",
60
+ schema: z.unknown(),
61
+ representation: "opaque",
62
+ coercion: {
63
+ parseValue: (value) => value,
64
+ parseLiteral: scalarLiteralValue,
65
+ serialize: (value) => value
66
+ }
67
+ });
68
+ //#endregion
69
+ //#region src/scalars/declarations/date-time.ts
70
+ const dateTimeScalar = defineCatalogScalar({
71
+ example: "2024-01-01T00:00:00.000Z",
72
+ name: "DateTime",
73
+ typescriptType: "string",
74
+ zodSource: "z.iso.datetime()",
75
+ schema: z.iso.datetime(),
76
+ representation: "string"
77
+ });
78
+ //#endregion
79
+ //#region src/scalars/pattern.ts
80
+ function matchesScalarPattern(pattern, value) {
81
+ return Reflect.apply(pattern.test.bind(pattern), void 0, [value]) === true;
82
+ }
83
+ //#endregion
84
+ //#region src/scalars/declarations/address.ts
85
+ const addressScalar = defineCatalogScalar({
86
+ example: "eip155:0x0000000000000000000000000000000000000000",
87
+ name: "Address",
88
+ typescriptType: "`${string}:0x${string}`",
89
+ zodSource: "z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))",
90
+ schema: z.custom((val) => matchesScalarPattern(/^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/, val)),
91
+ representation: "string"
92
+ });
93
+ //#endregion
94
+ //#region src/scalars/declarations/attachment-ref.ts
95
+ const attachmentRefScalar = defineCatalogScalar({
96
+ example: "attachment://v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
97
+ name: "AttachmentRef",
98
+ typescriptType: "`attachment://v${number}:${string}`",
99
+ zodSource: "z.custom<`attachment://v${number}:${string}`>((val) => /^attachment:\\/\\/v\\d+:.+$/.test(val as string))",
100
+ schema: z.custom((val) => matchesScalarPattern(/^attachment:\/\/v\d+:.+$/, val)),
101
+ representation: "string"
102
+ });
103
+ //#endregion
104
+ //#region src/scalars/coercion.ts
105
+ /** Runs `schema` on every path; `readLiteral` turns an inline literal into its value first. */
106
+ function validatingCoercion(schema, readLiteral) {
107
+ const parse = (value) => schema.parse(value);
108
+ return {
109
+ parseValue: parse,
110
+ parseLiteral: (node) => parse(readLiteral(node)),
111
+ serialize: parse
112
+ };
113
+ }
114
+ //#endregion
115
+ //#region src/scalars/declarations/amounts.ts
116
+ function floatAmountCoercion(schema) {
117
+ return validatingCoercion(schema, (node) => floatOnlyNumber(node, "value"));
118
+ }
119
+ function stringAmountCoercion(schema) {
120
+ return validatingCoercion(schema, (node) => {
121
+ const fields = objectFields(node);
122
+ const value = literalString(fields.get("value"), "value");
123
+ if (!/^\d+(\.\d+)?$/.test(value)) throw new TypeError("value must be a numeric string.");
124
+ return {
125
+ unit: literalString(fields.get("unit"), "unit"),
126
+ value
127
+ };
128
+ });
129
+ }
130
+ //#endregion
131
+ //#region src/scalars/declarations/amount-tokens.ts
132
+ const schema$6 = z.number();
133
+ const amountTokensScalar = defineCatalogScalar({
134
+ name: "Amount_Tokens",
135
+ typescriptType: "number",
136
+ zodSource: "z.number()",
137
+ schema: schema$6,
138
+ representation: "number",
139
+ coercion: floatAmountCoercion(schema$6)
140
+ });
141
+ //#endregion
142
+ //#region src/scalars/declarations/ethereum-address.ts
143
+ const ethereumAddressScalar = defineCatalogScalar({
144
+ name: "EthereumAddress",
145
+ typescriptType: "string",
146
+ zodSource: "z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: 'Invalid Ethereum address format' })",
147
+ schema: z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: "Invalid Ethereum address format" }),
148
+ representation: "string"
149
+ });
150
+ //#endregion
151
+ //#region src/scalars/declarations/email-address.ts
152
+ const emailAddressScalar = defineCatalogScalar({
153
+ name: "EmailAddress",
154
+ typescriptType: "string",
155
+ zodSource: "z.email()",
156
+ schema: z.email(),
157
+ representation: "string"
158
+ });
159
+ //#endregion
160
+ //#region src/scalars/declarations/amount-percentage.ts
161
+ const schema$5 = z.number();
162
+ const amountPercentageScalar = defineCatalogScalar({
163
+ name: "Amount_Percentage",
164
+ typescriptType: "number",
165
+ zodSource: "z.number()",
166
+ schema: schema$5,
167
+ representation: "number",
168
+ coercion: floatAmountCoercion(schema$5)
169
+ });
170
+ //#endregion
171
+ //#region src/scalars/declarations/date.ts
172
+ const dateScalar = defineCatalogScalar({
173
+ example: "2024-01-01T00:00:00.000Z",
174
+ name: "Date",
175
+ typescriptType: "string",
176
+ zodSource: "z.iso.datetime()",
177
+ schema: z.iso.datetime(),
178
+ representation: "string"
179
+ });
180
+ //#endregion
181
+ //#region src/scalars/declarations/url.ts
182
+ const urlScalar = defineCatalogScalar({
183
+ example: "https://example.com",
184
+ name: "URL",
185
+ typescriptType: "string",
186
+ zodSource: "z.url()",
187
+ schema: z.url(),
188
+ representation: "string"
189
+ });
190
+ //#endregion
191
+ //#region src/scalars/declarations/amount-money.ts
192
+ const schema$4 = z.number();
193
+ const amountMoneyScalar = defineCatalogScalar({
194
+ name: "Amount_Money",
195
+ typescriptType: "number",
196
+ zodSource: "z.number()",
197
+ schema: schema$4,
198
+ representation: "number",
199
+ coercion: floatAmountCoercion(schema$4)
200
+ });
201
+ //#endregion
202
+ //#region src/scalars/declarations/olabel.ts
203
+ const olabelScalar = defineCatalogScalar({
204
+ name: "OLabel",
205
+ typescriptType: "string",
206
+ zodSource: "z.string()",
207
+ schema: z.string(),
208
+ representation: "string"
209
+ });
210
+ //#endregion
211
+ //#region src/scalars/declarations/currency.ts
212
+ const currencyScalar = defineCatalogScalar({
213
+ name: "Currency",
214
+ typescriptType: "string",
215
+ zodSource: "z.string()",
216
+ schema: z.string(),
217
+ representation: "string"
218
+ });
219
+ //#endregion
220
+ //#region src/scalars/declarations/phid.ts
221
+ const phidScalar = defineCatalogScalar({
222
+ name: "PHID",
223
+ typescriptType: "string",
224
+ zodSource: "z.string()",
225
+ schema: z.string(),
226
+ representation: "string"
227
+ });
228
+ //#endregion
229
+ //#region src/scalars/declarations/oid.ts
230
+ const oidScalar = defineCatalogScalar({
231
+ name: "OID",
232
+ typescriptType: "string",
233
+ zodSource: "z.string()",
234
+ schema: z.string(),
235
+ representation: "string"
236
+ });
237
+ //#endregion
238
+ //#region src/scalars/declarations/amount-fiat.ts
239
+ const schema$3 = z.object({
240
+ unit: z.string(),
241
+ value: z.number()
242
+ });
243
+ const amountFiatScalar = defineCatalogScalar({
244
+ name: "Amount_Fiat",
245
+ typescriptType: "{ unit: string, value: number }",
246
+ zodSource: "z.object({ unit: z.string(), value: z.number() })",
247
+ schema: schema$3,
248
+ representation: "json-object",
249
+ coercion: validatingCoercion(schema$3, (node) => {
250
+ const fields = objectFields(node);
251
+ return {
252
+ unit: literalString(fields.get("unit"), "unit"),
253
+ value: floatOnlyNumber(fields.get("value"), "value")
254
+ };
255
+ })
256
+ });
257
+ //#endregion
258
+ //#region src/scalars/declarations/amount-currency.ts
259
+ const schema$2 = z.object({
260
+ unit: z.string(),
261
+ value: z.string()
262
+ });
263
+ const amountCurrencyScalar = defineCatalogScalar({
264
+ name: "Amount_Currency",
265
+ typescriptType: "{ unit: string, value: string }",
266
+ zodSource: "z.object({ unit: z.string(), value: z.string()})",
267
+ schema: schema$2,
268
+ representation: "json-object",
269
+ coercion: stringAmountCoercion(schema$2)
270
+ });
271
+ //#endregion
272
+ //#region src/scalars/declarations/amount-crypto.ts
273
+ const schema$1 = z.object({
274
+ unit: z.string(),
275
+ value: z.string()
276
+ });
277
+ const amountCryptoScalar = defineCatalogScalar({
278
+ name: "Amount_Crypto",
279
+ typescriptType: "{ unit: string, value: string }",
280
+ zodSource: "z.object({ unit: z.string(), value: z.string() })",
281
+ schema: schema$1,
282
+ representation: "json-object",
283
+ coercion: stringAmountCoercion(schema$1)
284
+ });
285
+ //#endregion
286
+ //#region src/scalars/declarations/amount.ts
287
+ const schema = z.object({
288
+ unit: z.string().optional(),
289
+ value: z.number()
290
+ });
291
+ //#endregion
292
+ //#region src/scalars/catalog.ts
293
+ const declarations = [
294
+ unknownScalar,
295
+ dateTimeScalar,
296
+ addressScalar,
297
+ attachmentRefScalar,
298
+ amountTokensScalar,
299
+ ethereumAddressScalar,
300
+ emailAddressScalar,
301
+ amountPercentageScalar,
302
+ dateScalar,
303
+ urlScalar,
304
+ amountMoneyScalar,
305
+ olabelScalar,
306
+ currencyScalar,
307
+ phidScalar,
308
+ oidScalar,
309
+ amountFiatScalar,
310
+ amountCurrencyScalar,
311
+ amountCryptoScalar,
312
+ defineCatalogScalar({
313
+ name: "Amount",
314
+ typescriptType: "{ unit?: string, value?: number }",
315
+ zodSource: "z.object({ unit: z.string().optional(), value: z.number() })",
316
+ schema,
317
+ representation: "json-object",
318
+ coercion: validatingCoercion(schema, (node) => {
319
+ const fields = objectFields(node);
320
+ const unit = fields.get("unit");
321
+ return {
322
+ unit: unit === void 0 ? void 0 : literalString(unit, "unit"),
323
+ value: floatOnlyNumber(fields.get("value"), "value")
324
+ };
325
+ })
326
+ }),
327
+ defineCatalogScalar({
328
+ name: "Upload",
329
+ typescriptType: "File",
330
+ zodSource: "z.any()",
331
+ schema: z.any(),
332
+ representation: "opaque",
333
+ coercion: {
334
+ parseValue: (value) => value,
335
+ parseLiteral: () => {
336
+ throw new TypeError("Upload literals are not supported.");
337
+ },
338
+ serialize: (value) => value
339
+ }
340
+ }),
341
+ defineCatalogScalar({
342
+ name: "JSONObject",
343
+ typescriptType: null,
344
+ zodSource: null,
345
+ schema: z.record(z.string(), z.unknown()),
346
+ representation: "json-object"
347
+ })
348
+ ];
349
+ const scalarCatalog = Object.freeze([...declarations]);
350
+ const byName = new Map(scalarCatalog.map((definition) => [definition.name, definition]));
351
+ function getCatalogScalar(name) {
352
+ return byName.get(name);
353
+ }
354
+ const documentModelScalars = Object.freeze(scalarCatalog.filter((definition) => definition.typescriptType !== null && definition.zodSource !== null));
355
+ //#endregion
356
+ //#region src/scalars/representation.ts
357
+ const shapeOfJsonType = {
358
+ null: "null",
359
+ string: "string",
360
+ number: "number",
361
+ integer: "number",
362
+ boolean: "boolean",
363
+ object: "json-object",
364
+ array: "json"
365
+ };
366
+ function shapeOfValue(value) {
367
+ if (value === null) return "null";
368
+ if (Array.isArray(value)) return "json";
369
+ if (typeof value === "object") return "json-object";
370
+ return shapeOfJsonType[typeof value];
371
+ }
372
+ /**
373
+ * The shapes a value of `node` can have, or `undefined` when zod states none.
374
+ * A union allows each branch's shapes; an intersection only those every
375
+ * stated member allows. `root` holds the `$defs` a local `$ref` names.
376
+ */
377
+ function jsonShapes(node, root, visiting = /* @__PURE__ */ new Set()) {
378
+ if (typeof node !== "object" || node === null || visiting.has(node)) return;
379
+ const inner = /* @__PURE__ */ new Set([...visiting, node]);
380
+ const record = node;
381
+ const { type, anyOf, oneOf, allOf } = record;
382
+ const stated = [];
383
+ const statedValues = (shapes) => {
384
+ if (!shapes.includes(void 0)) stated.push(new Set(shapes));
385
+ };
386
+ const not = record.not;
387
+ if (typeof not === "object" && not !== null && Object.keys(not).length === 0) stated.push(/* @__PURE__ */ new Set());
388
+ if (typeof type === "string" || Array.isArray(type)) statedValues([type].flat().map((name) => shapeOfJsonType[String(name)]));
389
+ if (Array.isArray(record.enum)) statedValues(record.enum.map(shapeOfValue));
390
+ if ("const" in record) statedValues([shapeOfValue(record.const)]);
391
+ const ref = record.$ref;
392
+ if (typeof ref === "string" && ref.startsWith("#/$defs/")) {
393
+ const defs = root.$defs;
394
+ const name = ref.slice(8).replaceAll("~1", "/").replaceAll("~0", "~");
395
+ const shapes = jsonShapes(defs?.[name], root, inner);
396
+ if (shapes) stated.push(shapes);
397
+ }
398
+ const branches = anyOf ?? oneOf;
399
+ if (Array.isArray(branches)) {
400
+ const shapes = branches.map((branch) => jsonShapes(branch, root, inner));
401
+ if (!shapes.includes(void 0)) stated.push(new Set(shapes.flatMap((set) => [...set ?? []])));
402
+ }
403
+ if (Array.isArray(allOf)) for (const member of allOf) {
404
+ const shapes = jsonShapes(member, root, inner);
405
+ if (shapes) stated.push(shapes);
406
+ }
407
+ if (stated.length === 0) return void 0;
408
+ const [first, ...rest] = stated;
409
+ return new Set([...first].filter((shape) => rest.every((set) => set.has(shape))));
410
+ }
411
+ /**
412
+ * The representation zod states for every output value of `schema`, or
413
+ * `undefined` when it cannot state one. One shape is that representation;
414
+ * several are `json`.
415
+ */
416
+ function statedRepresentation(schema) {
417
+ const jsonSchema = outputJsonSchema(schema);
418
+ const stated = jsonShapes(jsonSchema, jsonSchema);
419
+ if (stated === void 0) return void 0;
420
+ const shapes = [...stated].filter((shape) => shape !== "null");
421
+ if (shapes.length === 0) return void 0;
422
+ const [only, ...rest] = shapes;
423
+ return rest.length === 0 ? only : "json";
424
+ }
425
+ function outputJsonSchema(schema) {
426
+ try {
427
+ return z.toJSONSchema(schema, {
428
+ io: "output",
429
+ unrepresentable: "any"
430
+ });
431
+ } catch {
432
+ return {};
433
+ }
434
+ }
435
+ //#endregion
436
+ //#region src/scalars/define-scalar.ts
437
+ const inputKeys = /* @__PURE__ */ new Set([
438
+ "name",
439
+ "schema",
440
+ "description",
441
+ "example",
442
+ "representation"
443
+ ]);
444
+ const jsonRepresentations = /* @__PURE__ */ new Set([
445
+ "string",
446
+ "number",
447
+ "boolean",
448
+ "json-object",
449
+ "json"
450
+ ]);
451
+ const graphqlBuiltIns = /* @__PURE__ */ new Set([
452
+ "Int",
453
+ "Float",
454
+ "String",
455
+ "Boolean",
456
+ "ID"
457
+ ]);
458
+ const catalogNames = new Set(scalarCatalog.map((definition) => definition.name));
459
+ const graphqlName = /^[_A-Za-z][_0-9A-Za-z]*$/;
460
+ const refusals = [
461
+ (input) => {
462
+ const unknownKeys = Object.keys(input).filter((key) => !inputKeys.has(key));
463
+ return unknownKeys.length > 0 ? `unknown input key ${unknownKeys.join(", ")}; defineScalar accepts only name, schema, description, example and representation` : void 0;
464
+ },
465
+ ({ name }) => typeof name !== "string" || !graphqlName.test(name) || name.startsWith("__") ? "the name is not a valid GraphQL name" : void 0,
466
+ ({ name }) => graphqlBuiltIns.has(name) ? "the name is a GraphQL built-in scalar" : void 0,
467
+ ({ name }) => catalogNames.has(name) ? "the name is a catalog scalar" : void 0,
468
+ ({ schema }) => schema._zod.optin === "defaulted" || schema._zod.optout === "optional" ? "the schema accepts a missing value; nullability belongs in the SDL" : void 0
469
+ ];
470
+ function defineScalar(input) {
471
+ for (const refusal of refusals) {
472
+ const reason = refusal(input);
473
+ if (reason !== void 0) throw new Error(`Cannot define scalar "${String(input.name)}": ${reason}.`);
474
+ }
475
+ const { example, representation, ...definition } = input;
476
+ const schema = input.schema;
477
+ const parsedExample = example === void 0 ? void 0 : schema.safeParse(example);
478
+ if (parsedExample?.success === false) throw new Error(`Cannot define scalar "${input.name}": the example fails the schema: ${z.prettifyError(parsedExample.error)}`);
479
+ return defineCatalogScalar({
480
+ ...definition,
481
+ schema,
482
+ ...parsedExample && { example: parsedExample.data },
483
+ typescriptType: null,
484
+ zodSource: null,
485
+ representation: scalarRepresentation(input.name, schema, representation)
486
+ });
487
+ }
488
+ function scalarRepresentation(name, schema, declared) {
489
+ const derived = statedRepresentation(schema);
490
+ if (declared === void 0) return derived ?? "json";
491
+ if (!jsonRepresentations.has(declared)) throw new Error(`Cannot define scalar "${name}": representation must be one of ${[...jsonRepresentations].join(", ")}.`);
492
+ const representation = declared;
493
+ if (derived !== void 0 && derived !== representation) throw new Error(`Cannot define scalar "${name}": the schema's values are ${derived}, so representation cannot be ${representation}.`);
494
+ return representation;
495
+ }
496
+ //#endregion
497
+ export { SCALAR_DEFINITION_VERSION, defineScalar, documentModelScalars, getCatalogScalar, isScalarDefinition, scalarCatalog, scalarDefinitionVersion };
498
+
499
+ //# sourceMappingURL=scalars.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scalars.js","names":["schema","schema","schema","schema","schema","schema"],"sources":["../src/scalars/types.ts","../src/scalars/define-catalog-scalar.ts","../src/scalars/scalar-literal.ts","../src/scalars/declarations/unknown.ts","../src/scalars/declarations/date-time.ts","../src/scalars/pattern.ts","../src/scalars/declarations/address.ts","../src/scalars/declarations/attachment-ref.ts","../src/scalars/coercion.ts","../src/scalars/declarations/amounts.ts","../src/scalars/declarations/amount-tokens.ts","../src/scalars/declarations/ethereum-address.ts","../src/scalars/declarations/email-address.ts","../src/scalars/declarations/amount-percentage.ts","../src/scalars/declarations/date.ts","../src/scalars/declarations/url.ts","../src/scalars/declarations/amount-money.ts","../src/scalars/declarations/olabel.ts","../src/scalars/declarations/currency.ts","../src/scalars/declarations/phid.ts","../src/scalars/declarations/oid.ts","../src/scalars/declarations/amount-fiat.ts","../src/scalars/declarations/amount-currency.ts","../src/scalars/declarations/amount-crypto.ts","../src/scalars/declarations/amount.ts","../src/scalars/declarations/upload.ts","../src/scalars/declarations/json-object.ts","../src/scalars/catalog.ts","../src/scalars/representation.ts","../src/scalars/define-scalar.ts"],"sourcesContent":["import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\n\nexport const SCALAR_DEFINITION = Symbol.for(\"powerhouse.scalar-definition\");\nexport const SCALAR_DEFINITION_VERSION = 1;\n\n/** The wire shape of a scalar's values. */\nexport type ScalarRepresentation =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"json-object\"\n | \"json\"\n | \"opaque\";\n\n/** The GraphQL coercion of a scalar: variables, inline literals, and output. */\nexport type ScalarCoercion<TValue> = {\n readonly parseValue: (input: unknown) => TValue;\n readonly parseLiteral: (node: ScalarLiteralNode) => TValue;\n readonly serialize: (value: unknown) => unknown;\n};\n\nexport type ScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = {\n readonly [SCALAR_DEFINITION]: typeof SCALAR_DEFINITION_VERSION;\n readonly name: TName;\n readonly description?: string;\n readonly schema: z.ZodType<TValue>;\n readonly typescriptType: string | null;\n readonly zodSource: string | null;\n readonly example?: TValue;\n /**\n * The wire shape of a value. It picks the literal kinds a derived coercion\n * accepts. A definition from a release before this field lacks it.\n */\n readonly representation?: ScalarRepresentation;\n /** Absent means derived: `schema` runs on every path and only the literal kinds of `representation` parse. */\n readonly coercion?: ScalarCoercion<TValue>;\n};\n\n/** A definition this release made, with its representation filled. */\nexport type DescribedScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = ScalarDefinition<TName, TValue> & {\n readonly representation: ScalarRepresentation;\n};\n\nexport type ScalarValue<T> =\n T extends ScalarDefinition<string, infer V> ? V : never;\n\n/** The definition format version `value` is branded with, if it has a brand. */\nexport function scalarDefinitionVersion(value: unknown): unknown {\n return typeof value === \"object\" &&\n value !== null &&\n SCALAR_DEFINITION in value\n ? value[SCALAR_DEFINITION]\n : undefined;\n}\n\nexport function isScalarDefinition(value: unknown): value is ScalarDefinition {\n return scalarDefinitionVersion(value) === SCALAR_DEFINITION_VERSION;\n}\n","import {\n type DescribedScalarDefinition,\n SCALAR_DEFINITION,\n SCALAR_DEFINITION_VERSION,\n} from \"./types.js\";\n\nexport function defineCatalogScalar<TName extends string, TValue>(\n input: Omit<\n DescribedScalarDefinition<TName, TValue>,\n typeof SCALAR_DEFINITION\n >,\n): DescribedScalarDefinition<TName, TValue> {\n return Object.freeze({\n ...input,\n [SCALAR_DEFINITION]: SCALAR_DEFINITION_VERSION,\n } satisfies DescribedScalarDefinition<TName, TValue>);\n}\n","/**\n * Closed literal grammar handed to `parseLiteral`. It mirrors the GraphQL\n * literal kinds the catalog supports so a declaration never needs graphql-js.\n */\nexport type ScalarLiteralNode =\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"float\"; readonly value: string }\n | { readonly kind: \"boolean\"; readonly value: boolean }\n | { readonly kind: \"null\" }\n | { readonly kind: \"enum\"; readonly value: string }\n | { readonly kind: \"list\"; readonly values: readonly ScalarLiteralNode[] }\n | {\n readonly kind: \"object\";\n readonly fields: readonly {\n readonly name: string;\n readonly value: ScalarLiteralNode;\n }[];\n }\n | { readonly kind: \"variable\"; readonly name: string };\n\nexport class ScalarLiteralVariableError extends TypeError {\n constructor(name: string) {\n super(\n `Variable $${name} cannot appear inside a scalar literal; GraphQL resolves variables before literal coercion.`,\n );\n this.name = \"ScalarLiteralVariableError\";\n }\n}\n\n/** Converts a literal node to its runtime value. A variable anywhere throws. */\nexport function scalarLiteralValue(node: ScalarLiteralNode): unknown {\n switch (node.kind) {\n case \"string\":\n case \"enum\":\n return node.value;\n case \"int\":\n case \"float\":\n return Number(node.value);\n case \"boolean\":\n return node.value;\n case \"null\":\n return null;\n case \"list\":\n return node.values.map(scalarLiteralValue);\n case \"object\":\n return Object.fromEntries(\n node.fields.map((field) => [\n field.name,\n scalarLiteralValue(field.value),\n ]),\n );\n case \"variable\":\n throw new ScalarLiteralVariableError(node.name);\n }\n}\n\nexport function objectFields(\n node: ScalarLiteralNode,\n): ReadonlyMap<string, ScalarLiteralNode> {\n if (node.kind !== \"object\")\n throw new TypeError(\"Value must be an object literal.\");\n return new Map(node.fields.map((field) => [field.name, field.value]));\n}\n\nexport function literalString(\n node: ScalarLiteralNode | undefined,\n field: string,\n): string {\n if (node?.kind !== \"string\")\n throw new TypeError(`${field} must be a string literal.`);\n return node.value;\n}\n\nexport function floatOnlyNumber(\n node: ScalarLiteralNode | undefined,\n field: string,\n): number {\n if (node?.kind !== \"float\")\n throw new TypeError(`${field} must be a float literal.`);\n return Number.parseFloat(node.value);\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { scalarLiteralValue } from \"../scalar-literal.js\";\n\nexport const unknownScalar = defineCatalogScalar({\n name: \"Unknown\",\n typescriptType: \"unknown\",\n zodSource: \"z.unknown()\",\n schema: z.unknown(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: scalarLiteralValue,\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateTimeScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"DateTime\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","export function matchesScalarPattern(pattern: RegExp, value: unknown): boolean {\n return Reflect.apply(pattern.test.bind(pattern), undefined, [value]) === true;\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const addressScalar = defineCatalogScalar({\n example: \"eip155:0x0000000000000000000000000000000000000000\",\n name: \"Address\",\n typescriptType: \"`${string}:0x${string}`\",\n zodSource:\n \"z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))\",\n schema: z.custom<`${string}:0x${string}`>((val) =>\n matchesScalarPattern(/^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/, val),\n ),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const attachmentRefScalar = defineCatalogScalar({\n example:\n \"attachment://v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n name: \"AttachmentRef\",\n typescriptType: \"`attachment://v${number}:${string}`\",\n zodSource:\n \"z.custom<`attachment://v${number}:${string}`>((val) => /^attachment:\\\\/\\\\/v\\\\d+:.+$/.test(val as string))\",\n schema: z.custom<`attachment://v${number}:${string}`>((val) =>\n matchesScalarPattern(/^attachment:\\/\\/v\\d+:.+$/, val),\n ),\n representation: \"string\",\n});\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\nimport type { ScalarCoercion } from \"./types.js\";\n\n/** Runs `schema` on every path; `readLiteral` turns an inline literal into its value first. */\nexport function validatingCoercion<TValue>(\n schema: z.ZodType<TValue>,\n readLiteral: (node: ScalarLiteralNode) => unknown,\n): ScalarCoercion<TValue> {\n const parse = (value: unknown): TValue => schema.parse(value);\n return {\n parseValue: parse,\n parseLiteral: (node) => parse(readLiteral(node)),\n serialize: parse,\n };\n}\n","import type { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\n// The document-engineering scalar resolvers this catalog replaced parsed an\n// amount's number only from a float literal, so an integer literal such as 5\n// is refused even though the schema accepts 5. The host does not use this\n// coercion yet; it accepts 5.\nexport function floatAmountCoercion(schema: z.ZodType<number>) {\n return validatingCoercion(schema, (node) => floatOnlyNumber(node, \"value\"));\n}\n\nexport function stringAmountCoercion<TValue>(schema: z.ZodType<TValue>) {\n return validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const value = literalString(fields.get(\"value\"), \"value\");\n if (!/^\\d+(\\.\\d+)?$/.test(value)) {\n throw new TypeError(\"value must be a numeric string.\");\n }\n return { unit: literalString(fields.get(\"unit\"), \"unit\"), value };\n });\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountTokensScalar = defineCatalogScalar({\n name: \"Amount_Tokens\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const ethereumAddressScalar = defineCatalogScalar({\n name: \"EthereumAddress\",\n typescriptType: \"string\",\n zodSource:\n \"z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: 'Invalid Ethereum address format' })\",\n schema: z.string().regex(/^0x[a-fA-F0-9]{40}$/, {\n error: \"Invalid Ethereum address format\",\n }),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const emailAddressScalar = defineCatalogScalar({\n name: \"EmailAddress\",\n typescriptType: \"string\",\n zodSource: \"z.email()\",\n schema: z.email(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountPercentageScalar = defineCatalogScalar({\n name: \"Amount_Percentage\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"Date\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const urlScalar = defineCatalogScalar({\n example: \"https://example.com\",\n name: \"URL\",\n typescriptType: \"string\",\n zodSource: \"z.url()\",\n schema: z.url(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountMoneyScalar = defineCatalogScalar({\n name: \"Amount_Money\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const olabelScalar = defineCatalogScalar({\n name: \"OLabel\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const currencyScalar = defineCatalogScalar({\n name: \"Currency\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const phidScalar = defineCatalogScalar({\n name: \"PHID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const oidScalar = defineCatalogScalar({\n name: \"OID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.number() });\n\nexport const amountFiatScalar = defineCatalogScalar({\n name: \"Amount_Fiat\",\n typescriptType: \"{ unit: string, value: number }\",\n zodSource: \"z.object({ unit: z.string(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n return {\n unit: literalString(fields.get(\"unit\"), \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCurrencyScalar = defineCatalogScalar({\n name: \"Amount_Currency\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string()})\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCryptoScalar = defineCatalogScalar({\n name: \"Amount_Crypto\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string() })\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string().optional(), value: z.number() });\n\nexport const amountScalar = defineCatalogScalar({\n name: \"Amount\",\n typescriptType: \"{ unit?: string, value?: number }\",\n zodSource: \"z.object({ unit: z.string().optional(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const unit = fields.get(\"unit\");\n return {\n unit: unit === undefined ? undefined : literalString(unit, \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const uploadScalar = defineCatalogScalar({\n name: \"Upload\",\n typescriptType: \"File\",\n zodSource: \"z.any()\",\n schema: z.any(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: () => {\n throw new TypeError(\"Upload literals are not supported.\");\n },\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const jsonObjectScalar = defineCatalogScalar({\n name: \"JSONObject\",\n typescriptType: null,\n zodSource: null,\n schema: z.record(z.string(), z.unknown()),\n representation: \"json-object\",\n});\n","import { unknownScalar } from \"./declarations/unknown.js\";\nimport { dateTimeScalar } from \"./declarations/date-time.js\";\nimport { addressScalar } from \"./declarations/address.js\";\nimport { attachmentRefScalar } from \"./declarations/attachment-ref.js\";\nimport { amountTokensScalar } from \"./declarations/amount-tokens.js\";\nimport { ethereumAddressScalar } from \"./declarations/ethereum-address.js\";\nimport { emailAddressScalar } from \"./declarations/email-address.js\";\nimport { amountPercentageScalar } from \"./declarations/amount-percentage.js\";\nimport { dateScalar } from \"./declarations/date.js\";\nimport { urlScalar } from \"./declarations/url.js\";\nimport { amountMoneyScalar } from \"./declarations/amount-money.js\";\nimport { olabelScalar } from \"./declarations/olabel.js\";\nimport { currencyScalar } from \"./declarations/currency.js\";\nimport { phidScalar } from \"./declarations/phid.js\";\nimport { oidScalar } from \"./declarations/oid.js\";\nimport { amountFiatScalar } from \"./declarations/amount-fiat.js\";\nimport { amountCurrencyScalar } from \"./declarations/amount-currency.js\";\nimport { amountCryptoScalar } from \"./declarations/amount-crypto.js\";\nimport { amountScalar } from \"./declarations/amount.js\";\nimport { uploadScalar } from \"./declarations/upload.js\";\nimport { jsonObjectScalar } from \"./declarations/json-object.js\";\nimport type { DescribedScalarDefinition } from \"./types.js\";\n\nconst declarations = [\n unknownScalar,\n dateTimeScalar,\n addressScalar,\n attachmentRefScalar,\n amountTokensScalar,\n ethereumAddressScalar,\n emailAddressScalar,\n amountPercentageScalar,\n dateScalar,\n urlScalar,\n amountMoneyScalar,\n olabelScalar,\n currencyScalar,\n phidScalar,\n oidScalar,\n amountFiatScalar,\n amountCurrencyScalar,\n amountCryptoScalar,\n amountScalar,\n uploadScalar,\n jsonObjectScalar,\n] as const;\n\nexport type CatalogScalarDefinition = (typeof declarations)[number];\n\nexport const scalarCatalog: readonly DescribedScalarDefinition[] =\n Object.freeze([...declarations]);\n\nconst byName = new Map(\n scalarCatalog.map((definition) => [definition.name, definition]),\n);\n\nexport function getCatalogScalar(\n name: string,\n): DescribedScalarDefinition | undefined {\n return byName.get(name);\n}\n\ntype DocumentModelScalar = DescribedScalarDefinition & {\n readonly typescriptType: string;\n readonly zodSource: string;\n};\n\n// A model's SDL may use every catalog scalar codegen can type. JSONObject is\n// host-only, so it has neither a TypeScript type nor a zod source.\nexport const documentModelScalars: readonly DocumentModelScalar[] =\n Object.freeze(\n scalarCatalog.filter(\n (definition): definition is DocumentModelScalar =>\n definition.typescriptType !== null && definition.zodSource !== null,\n ),\n );\n","import { z } from \"zod\";\nimport type { ScalarRepresentation } from \"./types.js\";\n\n// defineScalar refuses a schema whose output is not JSON, so a package\n// scalar's values are never opaque.\nexport type JsonRepresentation = Exclude<ScalarRepresentation, \"opaque\">;\n\n// \"null\" is tracked through intersections and dropped before deciding: the\n// SDL owns nullability, so a null value never decides a representation.\ntype JsonShape = JsonRepresentation | \"null\";\n\nconst shapeOfJsonType: Readonly<Record<string, JsonShape | undefined>> = {\n null: \"null\",\n string: \"string\",\n number: \"number\",\n integer: \"number\",\n boolean: \"boolean\",\n object: \"json-object\",\n array: \"json\",\n};\n\nfunction shapeOfValue(value: unknown): JsonShape | undefined {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"json\";\n if (typeof value === \"object\") return \"json-object\";\n return shapeOfJsonType[typeof value];\n}\n\n/**\n * The shapes a value of `node` can have, or `undefined` when zod states none.\n * A union allows each branch's shapes; an intersection only those every\n * stated member allows. `root` holds the `$defs` a local `$ref` names.\n */\nfunction jsonShapes(\n node: unknown,\n root: Readonly<Record<string, unknown>>,\n visiting: ReadonlySet<unknown> = new Set(),\n): ReadonlySet<JsonShape> | undefined {\n if (typeof node !== \"object\" || node === null || visiting.has(node)) {\n return undefined;\n }\n const inner = new Set([...visiting, node]);\n const record = node as Record<string, unknown>;\n const { type, anyOf, oneOf, allOf } = record;\n const stated: ReadonlySet<JsonShape>[] = [];\n const statedValues = (shapes: (JsonShape | undefined)[]) => {\n if (!shapes.includes(undefined)) {\n stated.push(new Set(shapes as JsonShape[]));\n }\n };\n // zod writes z.never() as { not: {} }, which no value matches.\n const not = record.not;\n if (\n typeof not === \"object\" &&\n not !== null &&\n Object.keys(not).length === 0\n ) {\n stated.push(new Set());\n }\n if (typeof type === \"string\" || Array.isArray(type)) {\n statedValues([type].flat().map((name) => shapeOfJsonType[String(name)]));\n }\n if (Array.isArray(record.enum)) statedValues(record.enum.map(shapeOfValue));\n if (\"const\" in record) statedValues([shapeOfValue(record.const)]);\n const ref = record.$ref;\n if (typeof ref === \"string\" && ref.startsWith(\"#/$defs/\")) {\n const defs = root.$defs as Record<string, unknown> | undefined;\n // A JSON Pointer token escapes \"~\" as \"~0\" and \"/\" as \"~1\".\n const name = ref\n .slice(\"#/$defs/\".length)\n .replaceAll(\"~1\", \"/\")\n .replaceAll(\"~0\", \"~\");\n const shapes = jsonShapes(defs?.[name], root, inner);\n if (shapes) stated.push(shapes);\n }\n const branches = anyOf ?? oneOf;\n if (Array.isArray(branches)) {\n const shapes = branches.map((branch) => jsonShapes(branch, root, inner));\n if (!shapes.includes(undefined)) {\n stated.push(new Set(shapes.flatMap((set) => [...(set ?? [])])));\n }\n }\n if (Array.isArray(allOf)) {\n for (const member of allOf) {\n const shapes = jsonShapes(member, root, inner);\n if (shapes) stated.push(shapes);\n }\n }\n if (stated.length === 0) return undefined;\n const [first, ...rest] = stated;\n return new Set(\n [...first].filter((shape) => rest.every((set) => set.has(shape))),\n );\n}\n\n/**\n * The representation zod states for every output value of `schema`, or\n * `undefined` when it cannot state one. One shape is that representation;\n * several are `json`.\n */\nexport function statedRepresentation(\n schema: z.ZodType,\n): JsonRepresentation | undefined {\n const jsonSchema = outputJsonSchema(schema);\n const stated = jsonShapes(jsonSchema, jsonSchema);\n if (stated === undefined) return undefined;\n const shapes = [...stated].filter((shape) => shape !== \"null\");\n if (shapes.length === 0) return undefined;\n const [only, ...rest] = shapes;\n return rest.length === 0 ? only : \"json\";\n}\n\nfunction outputJsonSchema(schema: z.ZodType): Record<string, unknown> {\n try {\n return z.toJSONSchema(schema, { io: \"output\", unrepresentable: \"any\" });\n } catch {\n return {};\n }\n}\n","import { z } from \"zod\";\nimport { scalarCatalog } from \"./catalog.js\";\nimport { defineCatalogScalar } from \"./define-catalog-scalar.js\";\nimport {\n type JsonRepresentation,\n statedRepresentation,\n} from \"./representation.js\";\nimport type { DescribedScalarDefinition } from \"./types.js\";\n\ntype Json = string | number | boolean | null | Json[] | { [key: string]: Json };\n\ntype OutputIsAny = {\n \"defineScalar refuses this schema: its output is any\": never;\n};\ntype AcceptsMissingValue = {\n \"defineScalar refuses this schema: it accepts a missing value; nullability belongs in the SDL\": never;\n};\ntype OutputCanBeNull = {\n \"defineScalar refuses this schema: its output can be null; nullability belongs in the SDL\": never;\n};\ntype OutputIsNotJson = {\n \"defineScalar refuses this schema: its output must be JSON\": never;\n};\ntype OutputFailsSchema = {\n \"defineScalar refuses this schema: its output must pass the schema again\": never;\n};\n\n// zod marks .default() and .prefault() with optin \"defaulted\" and .optional()\n// and .nullish() with optout \"optional\". z.coerce and z.preprocess take\n// `unknown`, which includes undefined, so for them only the markers count.\ntype TakesMissingValue<S extends z.ZodType> =\n S[\"_zod\"][\"optin\"] extends \"defaulted\"\n ? true\n : S[\"_zod\"][\"optout\"] extends \"optional\"\n ? true\n : unknown extends z.input<S>\n ? false\n : undefined extends z.input<S>\n ? true\n : false;\n\ntype CanonicalSchema<S extends z.ZodType> = 0 extends 1 & z.output<S>\n ? OutputIsAny\n : TakesMissingValue<S> extends true\n ? AcceptsMissingValue\n : z.output<S> extends Json\n ? null extends z.output<S>\n ? OutputCanBeNull\n : z.output<S> extends z.input<S>\n ? S\n : OutputFailsSchema\n : OutputIsNotJson;\n\ntype ScalarInput<TName extends string, S extends z.ZodType> = {\n name: TName;\n schema: S & CanonicalSchema<S>;\n description?: string;\n example?: NoInfer<z.input<S>>;\n /** Only for a schema whose JSON shape zod cannot state, such as `z.custom`. */\n representation?: JsonRepresentation;\n};\n\nconst inputKeys = new Set([\n \"name\",\n \"schema\",\n \"description\",\n \"example\",\n \"representation\",\n]);\nconst jsonRepresentations: ReadonlySet<unknown> = new Set<JsonRepresentation>([\n \"string\",\n \"number\",\n \"boolean\",\n \"json-object\",\n \"json\",\n]);\nconst graphqlBuiltIns: ReadonlySet<unknown> = new Set([\n \"Int\",\n \"Float\",\n \"String\",\n \"Boolean\",\n \"ID\",\n]);\nconst catalogNames: ReadonlySet<unknown> = new Set(\n scalarCatalog.map((definition) => definition.name),\n);\nconst graphqlName = /^[_A-Za-z][_0-9A-Za-z]*$/;\n\ntype Refusal = (\n input: Readonly<Record<string, unknown>> & { readonly schema: z.ZodType },\n) => string | undefined;\n\nconst refusals: readonly Refusal[] = [\n (input) => {\n const unknownKeys = Object.keys(input).filter((key) => !inputKeys.has(key));\n return unknownKeys.length > 0\n ? `unknown input key ${unknownKeys.join(\", \")}; defineScalar accepts only name, schema, description, example and representation`\n : undefined;\n },\n ({ name }) =>\n typeof name !== \"string\" || !graphqlName.test(name) || name.startsWith(\"__\")\n ? \"the name is not a valid GraphQL name\"\n : undefined,\n ({ name }) =>\n graphqlBuiltIns.has(name)\n ? \"the name is a GraphQL built-in scalar\"\n : undefined,\n ({ name }) =>\n catalogNames.has(name) ? \"the name is a catalog scalar\" : undefined,\n ({ schema }) =>\n schema._zod.optin === \"defaulted\" || schema._zod.optout === \"optional\"\n ? \"the schema accepts a missing value; nullability belongs in the SDL\"\n : undefined,\n];\n\nexport function defineScalar<TName extends string, S extends z.ZodType>(\n input: ScalarInput<TName, S>,\n): DescribedScalarDefinition<TName, z.output<S>> {\n for (const refusal of refusals) {\n const reason = refusal(input);\n if (reason !== undefined) {\n throw new Error(\n `Cannot define scalar \"${String(input.name)}\": ${reason}.`,\n );\n }\n }\n const { example, representation, ...definition } = input;\n // TypeScript cannot relate a generic S to its own z.output<S>.\n const schema = input.schema as z.ZodType<z.output<S>>;\n const parsedExample =\n example === undefined ? undefined : schema.safeParse(example);\n if (parsedExample?.success === false) {\n throw new Error(\n `Cannot define scalar \"${input.name}\": the example fails the schema: ${z.prettifyError(parsedExample.error)}`,\n );\n }\n return defineCatalogScalar({\n ...definition,\n schema,\n ...(parsedExample && { example: parsedExample.data }),\n typescriptType: null,\n zodSource: null,\n representation: scalarRepresentation(input.name, schema, representation),\n });\n}\n\nfunction scalarRepresentation(\n name: string,\n schema: z.ZodType,\n declared: unknown,\n): JsonRepresentation {\n const derived = statedRepresentation(schema);\n if (declared === undefined) return derived ?? \"json\";\n if (!jsonRepresentations.has(declared)) {\n throw new Error(\n `Cannot define scalar \"${name}\": representation must be one of ${[...jsonRepresentations].join(\", \")}.`,\n );\n }\n const representation = declared as JsonRepresentation;\n if (derived !== undefined && derived !== representation) {\n throw new Error(\n `Cannot define scalar \"${name}\": the schema's values are ${derived}, so representation cannot be ${representation}.`,\n );\n }\n return representation;\n}\n"],"mappings":";;AAGA,MAAa,oBAAoB,OAAO,IAAI,8BAA8B;AAC1E,MAAa,4BAA4B;;AAkDzC,SAAgB,wBAAwB,OAAyB;CAC/D,OAAO,OAAO,UAAU,YACtB,UAAU,QACV,qBAAqB,QACnB,MAAM,qBACN,KAAA;AACN;AAEA,SAAgB,mBAAmB,OAA2C;CAC5E,OAAO,wBAAwB,KAAK,MAAA;AACtC;;;AC1DA,SAAgB,oBACd,OAI0C;CAC1C,OAAO,OAAO,OAAO;EACnB,GAAG;GACF,oBAAA;CACH,CAAoD;AACtD;;;ACKA,IAAa,6BAAb,cAAgD,UAAU;CACxD,YAAY,MAAc;EACxB,MACE,aAAa,KAAK,4FACpB;EACA,KAAK,OAAO;CACd;AACF;;AAGA,SAAgB,mBAAmB,MAAkC;CACnE,QAAQ,KAAK,MAAb;EACE,KAAK;EACL,KAAK,QACH,OAAO,KAAK;EACd,KAAK;EACL,KAAK,SACH,OAAO,OAAO,KAAK,KAAK;EAC1B,KAAK,WACH,OAAO,KAAK;EACd,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO,KAAK,OAAO,I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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document-model",
3
- "version": "6.2.3-dev.9",
3
+ "version": "6.2.3-dev.90",
4
4
  "license": "AGPL-3.0-only",
5
5
  "private": false,
6
6
  "files": [
@@ -13,6 +13,11 @@
13
13
  },
14
14
  "type": "module",
15
15
  "exports": {
16
+ "./scalars": {
17
+ "source": "./scalars.ts",
18
+ "import": "./dist/scalars.js",
19
+ "types": "./dist/scalars.d.ts"
20
+ },
16
21
  ".": {
17
22
  "source": "./index.ts",
18
23
  "import": "./dist/index.js",
@@ -45,15 +50,15 @@
45
50
  "@types/mime": "^4.0.0",
46
51
  "@types/node": "25.2.3",
47
52
  "change-case": "5.4.4",
48
- "jest": "^30.0.5",
53
+ "graphql": "^16",
49
54
  "mutative": "^1.0.5",
50
- "tsdown": "0.21.1",
51
- "tsx": "4.21.0",
52
- "vitest": "4.1.1",
53
- "zod": "4.3.6"
55
+ "tsdown": "0.23.0",
56
+ "tsx": "4.23.13",
57
+ "vitest": "5.0.3"
54
58
  },
55
59
  "dependencies": {
56
- "@powerhousedao/shared": "6.2.3-dev.9"
60
+ "@powerhousedao/shared": "6.2.3-dev.90",
61
+ "zod": "^4.5.4"
57
62
  },
58
63
  "description": "Powerhouse document model — foundational data structure for local-first, event-sourced documents with typed operations, reducers, and GraphQL schema validation.",
59
64
  "keywords": [
@@ -70,7 +75,7 @@
70
75
  "homepage": "https://academy.vetra.io/academy/Reference/DocumentModels",
71
76
  "scripts": {
72
77
  "tsc": "tsc",
73
- "lint": "eslint",
78
+ "lint": "cd ../.. && oxlint packages/document-model",
74
79
  "test": "vitest --run",
75
80
  "test:watch": "vitest watch",
76
81
  "build": "tsx ./build.ts"