solve-engine 2.27.0 → 2.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{EngineError-C-kBwYlN.d.cts → EngineError-CA2tiVaI.d.cts} +2 -0
- package/dist/{EngineError-C-kBwYlN.d.ts → EngineError-CA2tiVaI.d.ts} +2 -0
- package/dist/{Lexer-DqtnZMC5.d.ts → Lexer-B62Hn9I-.d.ts} +1 -1
- package/dist/{Lexer-DhGhoAa2.d.cts → Lexer-DOXatsjO.d.cts} +1 -1
- package/dist/{PackageCompatibility-fj_f7uqC.d.ts → PackageCompatibility-DT1IPlQx.d.ts} +1 -1
- package/dist/{PackageCompatibility-CNiTtC6S.d.cts → PackageCompatibility-DW18LqED.d.cts} +1 -1
- package/dist/{PackageRegistry-BHBCFswo.d.cts → PackageRegistry-CevYUzRn.d.cts} +3 -3
- package/dist/{PackageRegistry-CNZUwWHJ.d.ts → PackageRegistry-Dl9kNP14.d.ts} +3 -3
- package/dist/{VMBuiltins-kv4rr0y5.d.cts → VMBuiltins-AIivGl0a.d.cts} +1 -1
- package/dist/{VMBuiltins-CZiZRKn-.d.ts → VMBuiltins-CbuFfIgQ.d.ts} +1 -1
- package/dist/{VMCheckpoints-yun4ocSv.d.cts → VMCheckpoints-BVrJwfZY.d.cts} +1 -1
- package/dist/{VMCheckpoints-DXze6ypg.d.ts → VMCheckpoints-DFCl63K5.d.ts} +1 -1
- package/dist/{WorkerError-CfBJYueR.d.ts → WorkerError-BuO9MrRr.d.ts} +1 -1
- package/dist/{WorkerError-BLZyNq6M.d.cts → WorkerError-DDtwl4oH.d.cts} +1 -1
- package/dist/{chunk-GVL3ZMS7.cjs → chunk-2G3AW6OQ.cjs} +2 -2
- package/dist/{chunk-GVL3ZMS7.cjs.map → chunk-2G3AW6OQ.cjs.map} +1 -1
- package/dist/{chunk-BCR53EIL.js → chunk-2RLNVS6G.js} +2 -2
- package/dist/{chunk-BCR53EIL.js.map → chunk-2RLNVS6G.js.map} +1 -1
- package/dist/{chunk-TMQ37JQY.cjs → chunk-2YNRIT2L.cjs} +3 -3
- package/dist/{chunk-TMQ37JQY.cjs.map → chunk-2YNRIT2L.cjs.map} +1 -1
- package/dist/chunk-3LWK33TJ.js +3 -0
- package/dist/chunk-3LWK33TJ.js.map +1 -0
- package/dist/{chunk-TPPM4QSS.cjs → chunk-5J2XDCSV.cjs} +2 -2
- package/dist/{chunk-TPPM4QSS.cjs.map → chunk-5J2XDCSV.cjs.map} +1 -1
- package/dist/chunk-5NQE5JMU.cjs +2 -0
- package/dist/{chunk-QQHHZPEW.cjs.map → chunk-5NQE5JMU.cjs.map} +1 -1
- package/dist/{chunk-LTUYWJGO.js → chunk-6T5HPIZX.js} +2 -2
- package/dist/{chunk-LTUYWJGO.js.map → chunk-6T5HPIZX.js.map} +1 -1
- package/dist/{chunk-S3ODNMJS.js → chunk-7ASISMXA.js} +2 -2
- package/dist/{chunk-S3ODNMJS.js.map → chunk-7ASISMXA.js.map} +1 -1
- package/dist/{chunk-YG7UWQFV.js → chunk-7ZYYWSLT.js} +2 -2
- package/dist/{chunk-YG7UWQFV.js.map → chunk-7ZYYWSLT.js.map} +1 -1
- package/dist/{chunk-BLJ6E577.js → chunk-A7RRWNLE.js} +2 -2
- package/dist/{chunk-BLJ6E577.js.map → chunk-A7RRWNLE.js.map} +1 -1
- package/dist/{chunk-BCY2WY5P.js → chunk-APU5LON7.js} +3 -3
- package/dist/{chunk-BCY2WY5P.js.map → chunk-APU5LON7.js.map} +1 -1
- package/dist/{chunk-ESZNJQ2C.js → chunk-DDVDRWCK.js} +3 -3
- package/dist/{chunk-ESZNJQ2C.js.map → chunk-DDVDRWCK.js.map} +1 -1
- package/dist/{chunk-ZPHUTCJ5.cjs → chunk-FSNBYRNA.cjs} +3 -3
- package/dist/{chunk-ZPHUTCJ5.cjs.map → chunk-FSNBYRNA.cjs.map} +1 -1
- package/dist/{chunk-2SYYKQ4Q.cjs → chunk-GWEINEJG.cjs} +2 -2
- package/dist/{chunk-2SYYKQ4Q.cjs.map → chunk-GWEINEJG.cjs.map} +1 -1
- package/dist/{chunk-GXO7TSXQ.cjs → chunk-HTAT4MGN.cjs} +3 -3
- package/dist/chunk-HTAT4MGN.cjs.map +1 -0
- package/dist/{chunk-D4VBWPWN.js → chunk-I6WGOM3C.js} +2 -2
- package/dist/{chunk-D4VBWPWN.js.map → chunk-I6WGOM3C.js.map} +1 -1
- package/dist/{chunk-CL7DM2FX.js → chunk-IAL64FCP.js} +2 -2
- package/dist/{chunk-CL7DM2FX.js.map → chunk-IAL64FCP.js.map} +1 -1
- package/dist/{chunk-TC23XEAV.js → chunk-IEBWLNI5.js} +2 -2
- package/dist/{chunk-TC23XEAV.js.map → chunk-IEBWLNI5.js.map} +1 -1
- package/dist/{chunk-YSHWNCDH.cjs → chunk-IIBR4LVH.cjs} +4 -4
- package/dist/{chunk-YSHWNCDH.cjs.map → chunk-IIBR4LVH.cjs.map} +1 -1
- package/dist/{chunk-UVHD7BBC.js → chunk-JHHSQ2YR.js} +3 -3
- package/dist/{chunk-UVHD7BBC.js.map → chunk-JHHSQ2YR.js.map} +1 -1
- package/dist/{chunk-G2V33LFM.cjs → chunk-KYE5BWPN.cjs} +2 -2
- package/dist/{chunk-G2V33LFM.cjs.map → chunk-KYE5BWPN.cjs.map} +1 -1
- package/dist/{chunk-LQIRBP4Q.js → chunk-LV7PJ2MU.js} +2 -2
- package/dist/{chunk-LQIRBP4Q.js.map → chunk-LV7PJ2MU.js.map} +1 -1
- package/dist/{chunk-SE6ZCGZ5.cjs → chunk-MKBB7IVN.cjs} +2 -2
- package/dist/{chunk-SE6ZCGZ5.cjs.map → chunk-MKBB7IVN.cjs.map} +1 -1
- package/dist/{chunk-LE6WZLJ4.js → chunk-MONPHAHO.js} +2 -2
- package/dist/{chunk-LE6WZLJ4.js.map → chunk-MONPHAHO.js.map} +1 -1
- package/dist/{chunk-ZC2NPRLO.js → chunk-N22D5ZD4.js} +3 -3
- package/dist/{chunk-ZC2NPRLO.js.map → chunk-N22D5ZD4.js.map} +1 -1
- package/dist/{chunk-GJZIJK2Q.cjs → chunk-O5ZLOZPH.cjs} +2 -2
- package/dist/{chunk-GJZIJK2Q.cjs.map → chunk-O5ZLOZPH.cjs.map} +1 -1
- package/dist/{chunk-Y7XRA2EV.js → chunk-OKSAUK5C.js} +2 -2
- package/dist/{chunk-Y7XRA2EV.js.map → chunk-OKSAUK5C.js.map} +1 -1
- package/dist/{chunk-RRUGQ6DM.js → chunk-OLATJABN.js} +2 -2
- package/dist/{chunk-RRUGQ6DM.js.map → chunk-OLATJABN.js.map} +1 -1
- package/dist/{chunk-REZQFPVX.js → chunk-POIHAKBX.js} +2 -2
- package/dist/{chunk-REZQFPVX.js.map → chunk-POIHAKBX.js.map} +1 -1
- package/dist/{chunk-AZX4NTYN.cjs → chunk-QXGKONTZ.cjs} +3 -3
- package/dist/{chunk-AZX4NTYN.cjs.map → chunk-QXGKONTZ.cjs.map} +1 -1
- package/dist/{chunk-VQO54ZMA.js → chunk-RRJ77SF6.js} +2 -2
- package/dist/{chunk-VQO54ZMA.js.map → chunk-RRJ77SF6.js.map} +1 -1
- package/dist/{chunk-O5PO4D2A.cjs → chunk-RVNW627Y.cjs} +2 -2
- package/dist/{chunk-O5PO4D2A.cjs.map → chunk-RVNW627Y.cjs.map} +1 -1
- package/dist/{chunk-CQLCTKMX.cjs → chunk-TTHCH7V2.cjs} +2 -2
- package/dist/{chunk-CQLCTKMX.cjs.map → chunk-TTHCH7V2.cjs.map} +1 -1
- package/dist/{chunk-6EYKVQT3.cjs → chunk-U7CNADCJ.cjs} +2 -2
- package/dist/{chunk-6EYKVQT3.cjs.map → chunk-U7CNADCJ.cjs.map} +1 -1
- package/dist/{chunk-FDKTESBC.cjs → chunk-UBKWHRFL.cjs} +2 -2
- package/dist/{chunk-FDKTESBC.cjs.map → chunk-UBKWHRFL.cjs.map} +1 -1
- package/dist/{chunk-ZSLVLMO5.cjs → chunk-UMW5PO42.cjs} +2 -2
- package/dist/{chunk-ZSLVLMO5.cjs.map → chunk-UMW5PO42.cjs.map} +1 -1
- package/dist/{chunk-7RC6RBS6.cjs → chunk-W5BBKLNS.cjs} +2 -2
- package/dist/{chunk-7RC6RBS6.cjs.map → chunk-W5BBKLNS.cjs.map} +1 -1
- package/dist/{chunk-ZDJTDFTR.cjs → chunk-WXOJ3DS3.cjs} +2 -2
- package/dist/{chunk-ZDJTDFTR.cjs.map → chunk-WXOJ3DS3.cjs.map} +1 -1
- package/dist/chunk-YIXCPLCN.cjs +3 -0
- package/dist/chunk-YIXCPLCN.cjs.map +1 -0
- package/dist/{chunk-ZE5KKMBV.cjs → chunk-YLTNXYA7.cjs} +2 -2
- package/dist/{chunk-ZE5KKMBV.cjs.map → chunk-YLTNXYA7.cjs.map} +1 -1
- package/dist/{chunk-VB6QMU2W.js → chunk-Z5DA5UXY.js} +3 -3
- package/dist/chunk-Z5DA5UXY.js.map +1 -0
- package/dist/{chunk-HANGBVEE.js → chunk-Z5VBXZ4A.js} +2 -2
- package/dist/{chunk-HANGBVEE.js.map → chunk-Z5VBXZ4A.js.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +6 -6
- package/dist/engine.d.ts +6 -6
- package/dist/engine.js +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/language.d.cts +5 -5
- package/dist/language.d.ts +5 -5
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +4 -4
- package/dist/packages.d.ts +4 -4
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.js +1 -1
- package/dist/temporal.cjs +1 -1
- package/dist/temporal.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +5 -5
- package/dist/testing.d.ts +5 -5
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +3 -3
- package/dist/vm.d.ts +3 -3
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +5 -5
- package/dist/worker.d.ts +5 -5
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DFMAZ6XM.cjs +0 -3
- package/dist/chunk-DFMAZ6XM.cjs.map +0 -1
- package/dist/chunk-GXO7TSXQ.cjs.map +0 -1
- package/dist/chunk-PQFI55AC.js +0 -3
- package/dist/chunk-PQFI55AC.js.map +0 -1
- package/dist/chunk-QQHHZPEW.cjs +0 -2
- package/dist/chunk-VB6QMU2W.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/EngineError.ts","../src/errors/Result.ts","../src/errors/ErrorCode.ts"],"names":["ErrorCategory","_EngineError","category","init","recoverable","skipStack","errorCtor","previousLimit","chain","current","lines","EngineError","ErrorFactory","_ErrorFactory","defaultRecoverable","codeOrInit","message","context","normalizeUnknownError","error","ok","value","err","isOk","r","isErr","map","fn","mapErr","andThen","unwrapOr","fallback","match","arms","combine","results","values","throwIfErr","tryCatch","normalize","e","tryCatchAsync","CoreErrorCodes","DatetimeErrorCodes"],"mappings":"aA6BO,IAAKA,OAEVA,CAAAA,CAAA,OAAA,CAAU,UAEVA,CAAAA,CAAA,SAAA,CAAY,YAEZA,CAAAA,CAAA,UAAA,CAAa,aAEbA,CAAAA,CAAA,QAAA,CAAW,WAEXA,CAA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,qBAAA,CAAuB,uBAAA,CAGvB,iBAAkB,kBAAA,CAClB,aAAA,CAAe,eACjB,CAAA,CAgBaC,EAAqB,CAEhC,qBAAA,CAAuB,wBAEvB,wBAAA,CAA0B,0BAAA,CAE1B,kBAAmB,mBACrB","file":"chunk-HTAT4MGN.cjs","sourcesContent":["/**\n * The engine's structured error type, the \"Rust/Go-style, verbose, easy to\n * tell the issue\" half of the error-handling redesign (the other half is\n * `Result.ts`).\n *\n * Historical note: an earlier version of this class (`UnifiedErrorFramework.ts`,\n * still the import path most of the codebase uses. See that file, now a\n * pure re-export barrel) had a much larger field set (`severity`,\n * `recovery`, a 5-value enum, `ErrorRecoveryManager`) that was almost\n * entirely dead: nothing downstream ever read `.severity`/`.recovery`,\n * only `.message` reliably survived to a caller. This version is smaller\n * and deliberately keeps only fields something actually consumes.\n */\n\nimport type { ErrorCode } from \"@solve-js/errors/ErrorCode\";\n\n/** A character-offset (and optional line/col) span into the original expression text, for a future \"underline the offending token\" UI, not yet wired to one. */\nexport interface SourceSpan {\n start: number;\n end: number;\n line?: number;\n col?: number;\n}\n\n/**\n * Error classification, kept from the original framework, now actually\n * consulted: it's the `format()` header and lets host code group errors\n * by pipeline stage without string-matching `.code`.\n */\nexport enum ErrorCategory {\n /** Errors during expression parsing. */\n PARSING = \"PARSING\",\n /** Errors during bytecode execution. */\n EXECUTION = \"EXECUTION\",\n /** Errors from input validation (safety limits, config). */\n VALIDATION = \"VALIDATION\",\n /** Errors from external services/APIs (currency rates, weather, stocks). */\n EXTERNAL = \"EXTERNAL\",\n /** Internal engine invariant violations. See `recoverable`'s doc comment. */\n INTERNAL = \"INTERNAL\",\n /** Configuration errors. */\n CONFIG = \"CONFIG\",\n}\n\n/** Fields accepted when constructing an {@link EngineError}. */\nexport interface EngineErrorInit {\n /** Catalog code. See `errors/ErrorCode.ts`. Not a free string: every code used by a BUILT-IN package should be registered there so `ErrorCodeCatalog.spec.ts` can catch collisions/typos. Third-party packages may still use any string here, `EngineError.code`'s runtime type is `string`. */\n code: ErrorCode | (string & {});\n /** Short, single-line, `Error.message`-compatible. Existing `.toThrow(/pattern/)`/`.message` assertions keep working against this field, richer detail goes in `expected`/`found`/`suggestion`, not crammed into this string. */\n message: string;\n /** What the parser/validator/VM expected to see, in plain words, e.g. \"a city name\", \"a 4-digit year\", \"end of expression\". */\n expected?: string;\n /** What was actually found instead, e.g. \"end of expression\", `NUMBER \"5\"`, the offending token's literal text. */\n found?: string;\n /** An actionable, worked-example fix, e.g. `e.g. \"weather in London\"`. Mirrors this codebase's best existing messages (`WEATHER_EXPECTED_CITY`, `AS_CONVERTER_EXPECTED_NAME`). */\n suggestion?: string;\n /**\n * Whether this engine instance is still usable. `true` for everything that\n * went wrong on ONE line, whether the line's fault (bad syntax, an unknown\n * variable, a safety limit exceeded), the environment's (an external API\n * down), or the engine's own (corrupted bytecode, a stack underflow from a\n * buggy plugin). `false` is for the far rarer case where there is no working\n * engine to go on with: a configuration or package-registration failure,\n * which is what `ErrorFactory.config()` is for and the only factory method\n * that still defaults to it.\n *\n * The category answers a different question, and the two used to be answered\n * as one. Category INTERNAL says whose fault this is, the engine's, worth\n * reporting as a bug. `recoverable` says whether the host may carry on, and\n * after an internal slip on one line it may:\n * `__tests__/hardening/RobustnessEngineLifecycle.spec.ts` alternates a\n * throwing line with a good one five hundred times and every answer stays\n * correct. Reporting that as `isFatal()` told a host the opposite, and a host\n * that honours the name would tear a document down over one bad line.\n *\n * This has never gated \"does evaluation of the rest of the document\n * continue\"; with this engine's per-line containment it always does, even for\n * a `recoverable: false` error (see `ARCHITECTURE.md`'s async-batcher/Tier-2\n * hardening notes). It gates what a host is TOLD. See\n * {@link EngineError.isFatal}.\n */\n recoverable?: boolean;\n /** Character-offset span into the source expression, when available. Not yet threaded through every call site, populate opportunistically, don't block on retrofitting every existing throw site. */\n span?: SourceSpan;\n /** Free-form structured context. The one field the pre-existing framework's real consumer (`ThreeTierEvaluator.ts`'s DAG-preservation-on-compile-error path) actually reads, kept name- and shape-compatible on purpose. */\n context?: Record<string, unknown>;\n /** The underlying error this one wraps, if any, passed straight through to native `Error.cause` (ES2022), so Node's default printer, most loggers, and `instanceof Error` tooling understand the chain for free. */\n cause?: unknown;\n}\n\n/**\n * The engine's structured error type. Still a real `Error` subclass (so\n * `throw`/`catch`/`instanceof Error` all keep working exactly as before),\n * but now every field except the removed `severity`/`recovery` pair is\n * something real code reads.\n */\nexport class EngineError extends Error {\n readonly category: ErrorCategory;\n readonly code: string;\n readonly expected?: string;\n readonly found?: string;\n readonly suggestion?: string;\n readonly recoverable: boolean;\n readonly span?: SourceSpan;\n readonly context?: Record<string, unknown>;\n readonly timestamp: Date;\n /**\n * Set explicitly (not via `super(message, {cause})`). This repo's\n * `tsconfig.json` targets ES6/ES5-ES7 lib, which predates TypeScript's\n * ES2022 `Error` constructor `cause`-option overload. `Error.prototype.cause`\n * is still a real runtime feature in every target this engine actually\n * runs in (Node 16.9+, all evergreen browsers, Electron/Obsidian's\n * bundled Chromium) regardless of the TS lib target used to type-check\n * against it, assigning it directly gets the same Node-printer/logger\n * interop with no build-config change needed.\n */\n readonly cause?: unknown;\n\n /**\n * Whether a recoverable error captures a JavaScript stack trace.\n *\n * Off, because a recoverable EngineError is a value rather than a fault. A\n * line of prose in a notepad is not an expression, so parsing it fails, and\n * that failure is the answer for that line rather than a bug to debug. The\n * engine builds one such error per non-expression line.\n *\n * Capturing a stack is not cheap, and its cost grows with how deep the stack\n * is when it happens. Measured through `parseDocument`, where the throw site\n * sits about a dozen frames down, each capture cost around 62 microseconds\n * and a 250-line document built 74 of them: a CPU profile put the\n * constructor at 46% of the whole pipeline, more than lexing, normalising,\n * parsing and executing put together.\n *\n * Turn it on to debug where a recoverable error is raised from. Errors that\n * are NOT recoverable always capture, since those are the genuine faults.\n *\n * @example\n * ```ts\n * EngineError.captureRecoverableStacks = true;\n * ```\n */\n static captureRecoverableStacks = false;\n\n constructor(category: ErrorCategory, init: EngineErrorInit) {\n // Before super(), which is legal as long as `this` is untouched. V8 reads\n // `Error.stackTraceLimit` while constructing the Error, so zeroing it\n // across the super() call is what actually skips the capture; there is no\n // per-instance switch for it.\n const recoverable = init.recoverable ?? true;\n const skipStack = recoverable && !EngineError.captureRecoverableStacks;\n // `stackTraceLimit` is a V8 extension, present in Node and every\n // Chromium-based browser but absent from the DOM lib, so it is reached\n // through a narrow local view rather than by widening the global type.\n // Where it does not exist, reading and writing it are both harmless and\n // the stack is captured as before.\n const errorCtor = Error as unknown as { stackTraceLimit?: number };\n const previousLimit = errorCtor.stackTraceLimit;\n if (skipStack) errorCtor.stackTraceLimit = 0;\n super(init.message);\n if (skipStack) errorCtor.stackTraceLimit = previousLimit;\n\n this.name = \"EngineError\";\n this.category = category;\n this.code = init.code;\n this.expected = init.expected;\n this.found = init.found;\n this.suggestion = init.suggestion;\n this.recoverable = recoverable;\n this.span = init.span;\n this.context = init.context;\n this.cause = init.cause;\n this.timestamp = new Date();\n // Only for the faults. super() has already captured a stack for those, and\n // this second call recaptures it purely to drop this constructor's own\n // frame; doing that for every error meant paying the whole cost twice.\n if (!skipStack && Error.captureStackTrace) {\n Error.captureStackTrace(this, EngineError);\n }\n }\n\n /** `!recoverable`. See `EngineErrorInit.recoverable`'s doc comment for what this actually gates (message framing/telemetry, not whether evaluation continues). */\n isFatal(): boolean {\n return !this.recoverable;\n }\n\n /** Walk `.cause` repeatedly, collecting the full chain (this error first). */\n causeChain(): unknown[] {\n const chain: unknown[] = [this];\n let current: unknown = this.cause;\n while (current !== undefined && current !== null) {\n chain.push(current);\n current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined;\n }\n return chain;\n }\n\n /**\n * Rust/Go-style multi-line renderer, the NEW thing a host/CLI/test\n * reaches for when it wants the full, verbose picture, as distinct from\n * `.message` (kept short and stable for existing assertions). Example:\n *\n * ```\n * error[WEATHER_EXPECTED_CITY]: Expected a city name after \"weather in\"\n * expected: a city name\n * found: end of expression\n * suggestion: e.g. \"weather in London\"\n * ```\n */\n format(): string {\n const lines = [`error[${this.code}]: ${this.message}`];\n if (this.expected) lines.push(` expected: ${this.expected}`);\n if (this.found) lines.push(` found: ${this.found}`);\n if (this.suggestion) lines.push(` suggestion: ${this.suggestion}`);\n return lines.join(\"\\n\");\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n category: this.category,\n code: this.code,\n message: this.message,\n expected: this.expected,\n found: this.found,\n suggestion: this.suggestion,\n recoverable: this.recoverable,\n span: this.span,\n context: this.context,\n timestamp: this.timestamp.toISOString(),\n };\n }\n}\n\n/**\n * Factory for creating classified `EngineError`s. Every method accepts\n * EITHER the original, minimal 3-arg shape (`code, message, context?`\n * every existing call site across the codebase keeps compiling unchanged)\n * OR the richer `EngineErrorInit` object (for `expected`/`found`/\n * `suggestion`/`recoverable`/`span`/`cause`), upgrade a call site to the\n * richer form only when you're already touching it, no separate churn\n * pass required.\n */\nexport class ErrorFactory {\n private static build(\n category: ErrorCategory,\n defaultRecoverable: boolean,\n codeOrInit: string | EngineErrorInit,\n message?: string,\n context?: Record<string, unknown>,\n ): EngineError {\n const init: EngineErrorInit =\n typeof codeOrInit === \"string\"\n ? { code: codeOrInit, message: message!, context }\n : codeOrInit;\n return new EngineError(category, { recoverable: defaultRecoverable, ...init });\n }\n\n static validation(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static validation(init: EngineErrorInit): EngineError;\n static validation(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.VALIDATION, true, codeOrInit, message, context);\n }\n\n static parsing(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static parsing(init: EngineErrorInit): EngineError;\n static parsing(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.PARSING, true, codeOrInit, message, context);\n }\n\n static execution(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static execution(init: EngineErrorInit): EngineError;\n static execution(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXECUTION, true, codeOrInit, message, context);\n }\n\n static external(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static external(init: EngineErrorInit): EngineError;\n static external(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXTERNAL, true, codeOrInit, message, context);\n }\n\n /**\n * Reserve for genuine engine-internal invariant violations (corrupted\n * bytecode, a stack underflow from a buggy plugin, an \"impossible\" state),\n * not for user-input errors: the category is a bug report.\n *\n * Defaults `recoverable: true` all the same, because every one of these sites\n * is an invariant that failed on ONE line and none of them leaves the engine\n * unusable. This used to default to `false`, which conflated \"the engine's\n * fault\" with \"the engine is finished\" and told a host to tear a document\n * down over a line it could simply have shown an error against. A site that\n * has looked at its own case and concluded the instance really is gone can\n * still pass `recoverable: false` explicitly. See {@link\n * EngineErrorInit.recoverable}.\n */\n static internal(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static internal(init: EngineErrorInit): EngineError;\n static internal(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.INTERNAL, true, codeOrInit, message, context);\n }\n\n /** Defaults `recoverable: false`, and is now the only method that does: a configuration or package-registration failure is the one class that leaves no working engine to carry on with, rather than one bad line in a document. */\n static config(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static config(init: EngineErrorInit): EngineError;\n static config(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.CONFIG, false, codeOrInit, message, context);\n }\n}\n\n/**\n * Normalize any thrown value into an `EngineError`, an `EngineError`\n * passes through as-is; a plain `Error` gets wrapped (message preserved,\n * original attached via `cause`); anything else becomes a generic\n * \"unknown error\" wrapping the stringified value. Used at every\n * throw-space/Result-space boundary (`Result.tryCatch`'s default\n * `normalize`, the VM's outer execution try/catch, `AsyncResolutionBatcher`'s\n * per-line containment) so a raw `TypeError` from a genuine engine bug\n * still surfaces as a structured, catalogued error instead of an opaque\n * uncaught exception.\n *\n * Both branches state RECOVERABLE explicitly, while keeping the INTERNAL\n * category. The two fields answer different questions and were previously\n * answering the same one:\n *\n * category INTERNAL whose fault is this? The engine's. Worth reporting.\n * recoverable is this engine instance still usable? Yes.\n *\n * Everything reaching here is by definition something the engine did not\n * anticipate on ONE line, and per-line containment means the next line\n * evaluates normally, which `__tests__/hardening/RobustnessEngineLifecycle`\n * demonstrates over hundreds of alternating failure/success pairs. Reporting\n * that as `isFatal()` told a host the opposite, and a host that honours the\n * name would tear a document down over a single bad line. The \"this is an\n * engine bug rather than your syntax\" signal a caller wants for telemetry is\n * the CATEGORY, which is unchanged.\n *\n * The flag is written out here rather than inherited from\n * `ErrorFactory.internal()`, which now defaults the same way, so that this\n * function's contract survives a future change to that default.\n */\nexport function normalizeUnknownError(error: unknown): EngineError {\n if (error instanceof EngineError) return error;\n if (error instanceof Error) {\n return ErrorFactory.internal({\n code: \"UNEXPECTED_ERROR\",\n message: error.message,\n context: { originalErrorName: error.name },\n cause: error,\n recoverable: true,\n });\n }\n return ErrorFactory.internal({\n code: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred\",\n context: { error: String(error) },\n recoverable: true,\n });\n}\n","import { type EngineError, normalizeUnknownError } from \"@solve-js/errors/EngineError\";\n\n/**\n * A Rust-style `Result<T, E>`, the value half of this engine's error-handling\n * redesign. `E` defaults to `EngineError` (this engine's structured error\n * type) but every combinator here is generic over `E`, so `Result` works\n * equally well for a domain that isn't `EngineError`-shaped.\n *\n * This exact shape used to live in `errors/UnifiedErrorFramework.ts` (kept\n * there as a barrel re-export for backward compatibility), moved here as\n * its own module because it's genuinely generic (no dependency on\n * `EngineError` beyond the default type parameter) and because the engine\n * is migrating callers to it incrementally: parsing/VM/package code that\n * expects \"a failure is a possibility, not an exception\" returns\n * `Result<T, EngineError>` instead of throwing; two explicit adapters\n * {@link throwIfErr} and {@link tryCatch}, are the sanctioned way to cross\n * the boundary between Result-based code and still-throw-based code during\n * the migration (and permanently, at the public API boundary. See\n * `ExpressionEngine.evaluateExpression()`'s documented throw contract).\n */\nexport type Result<T, E = EngineError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\n/** Wrap a successful value. */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/** Wrap a failure. */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Narrow a {@link Result} to its success arm.\n *\n * @param r - The result to test.\n * @returns True when it succeeded, narrowing `r` so `r.value` is reachable.\n */\nexport function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {\n return r.ok;\n}\n\n/**\n * Narrow a {@link Result} to its failure arm.\n *\n * @param r - The result to test.\n * @returns True when it failed, narrowing `r` so `r.error` is reachable.\n */\nexport function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {\n return !r.ok;\n}\n\n/** Transform the success value; a failure passes through untouched. */\nexport function map<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return r.ok ? ok(fn(r.value)) : r;\n}\n\n/** Transform the error; a success passes through untouched. */\nexport function mapErr<T, E, F>(r: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return r.ok ? r : err(fn(r.error));\n}\n\n/** Chain a Result-returning operation onto a success (a.k.a. flatMap/bind). */\nexport function andThen<T, U, E>(r: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return r.ok ? fn(r.value) : r;\n}\n\n/** Unwrap a success, or return `fallback` for a failure. Never throws. */\nexport function unwrapOr<T, E>(r: Result<T, E>, fallback: T): T {\n return r.ok ? r.value : fallback;\n}\n\n/** Exhaustive pattern-match, the `match`/`switch` a Rust enum gets for free. */\nexport function match<T, E, R>(r: Result<T, E>, arms: { ok: (value: T) => R; err: (error: E) => R }): R {\n return r.ok ? arms.ok(r.value) : arms.err(r.error);\n}\n\n/**\n * Combine several Results into one, succeeds with a tuple of all values\n * iff every input succeeded; otherwise fails with the FIRST error\n * encountered (left-to-right), matching this codebase's existing\n * fail-fast convention elsewhere (e.g. `BytecodeBuilder`'s constant-pool\n * limit checks).\n */\nexport function combine<T extends readonly unknown[], E>(\n results: { [K in keyof T]: Result<T[K], E> },\n): Result<T, E> {\n const values: unknown[] = [];\n for (const r of results as readonly Result<unknown, E>[]) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values as unknown as T);\n}\n\n/**\n * Cross from Result-space back to throw-space, the sanctioned boundary\n * adapter for callers (public API surface, older not-yet-migrated code,\n * tests) that still want exception-based control flow. Throws `r.error`\n * as-is (an `EngineError` is already a real `Error` subclass, so this\n * needs no wrapping).\n */\nexport function throwIfErr<T, E>(r: Result<T, E>): T {\n if (r.ok) return r.value;\n throw r.error;\n}\n\n/**\n * Cross from throw-space into Result-space, runs `fn`, converting any\n * thrown value into a Result via `normalize` (defaults to\n * {@link normalizeUnknownError}). The inverse of {@link throwIfErr}; the\n * pairing that lets Result-based and throw-based code interoperate during\n * an incremental migration instead of requiring a single flag-day rewrite.\n */\nexport function tryCatch<T>(\n fn: () => T,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Result<T, EngineError> {\n try {\n return ok(fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n\n/** Async sibling of {@link tryCatch}. */\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Promise<Result<T, EngineError>> {\n try {\n return ok(await fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n","/**\n * The built-in error-code catalog, one typed const object per domain\n * unioned together here for autocomplete/exhaustiveness in core engine\n * code. Deliberately NOT one central enum: `IEnginePackage` is documented\n * public SDK surface for third-party packages (see `api/PackageRegistry.ts`),\n * and a closed enum would block an external package author from defining\n * their own codes without editing this file. `EngineError.code`'s runtime\n * type stays `string` for exactly that reason. This catalog is for the\n * codes THIS repo owns and wants collision/typo checking on (see\n * `__tests__/errors/ErrorCodeCatalog.spec.ts`), not a hard runtime\n * whitelist.\n *\n * As each package migrates to `Result<void, EngineError>` (see this\n * session's error-handling-refactor plan, Phase 5), it should export its\n * own small `XxxErrorCodes` const object co-located with its parselets\n * exactly like `CoreErrorCodes` below, just scoped to one domain, and get\n * unioned into `ErrorCode` here. Until a package migrates, its existing\n * free-string codes keep working (ErrorFactory accepts any string); they\n * just aren't caught by the catalog's uniqueness/orphan checks yet.\n */\n\n/**\n * Codes used directly by the parser/VM/engine/errors layers themselves\n * confirmed against the current source, not aspirational. Grouped by\n * pipeline stage via the comments, not a naming prefix (these predate any\n * naming convention and renaming them is out of scope for introducing the\n * catalog, only NEW codes need to follow a scoped/prefixed style, see\n * `STACK_UNDERFLOW` etc. below).\n */\nexport const CoreErrorCodes = {\n // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──\n INVALID_NUMBER_LITERAL: \"INVALID_NUMBER_LITERAL\",\n /** A `\"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `\"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */\n UNTERMINATED_STRING: \"UNTERMINATED_STRING\",\n NO_PREFIX_PARSELET: \"NO_PREFIX_PARSELET\",\n UNEXPECTED_END_OF_INPUT: \"UNEXPECTED_END_OF_INPUT\",\n UNEXPECTED_TOKEN_TYPE: \"UNEXPECTED_TOKEN_TYPE\",\n NESTING_DEPTH_EXCEEDED: \"NESTING_DEPTH_EXCEEDED\",\n UNEXPECTED_END: \"UNEXPECTED_END\",\n UNEXPECTED_TRAILING_TOKEN: \"UNEXPECTED_TRAILING_TOKEN\",\n PARSE_ERROR: \"PARSE_ERROR\",\n TOO_MANY_NUMERIC_CONSTANTS: \"TOO_MANY_NUMERIC_CONSTANTS\",\n /** A raw bytecode operand outside 0 to 255, or a jump patch outside the emitted stream (`parser/BytecodeBuilder.ts`'s `emitIndex`, `emitByte`, `patchJump`). `build()` keeps one byte per operand, so 300 used to become 44 with no error and the program read the wrong constant or plugin function. A package-authoring fault, reported at compile time. */\n BYTECODE_OPERAND_OUT_OF_RANGE: \"BYTECODE_OPERAND_OUT_OF_RANGE\",\n TOO_MANY_STRING_CONSTANTS: \"TOO_MANY_STRING_CONSTANTS\",\n NO_MATCHING_PHRASE_ALTERNATIVE: \"NO_MATCHING_PHRASE_ALTERNATIVE\",\n INVALID_PHRASE_PATTERN: \"INVALID_PHRASE_PATTERN\",\n PHRASE_KEYWORD_MISMATCH: \"PHRASE_KEYWORD_MISMATCH\",\n /** User-defined-function definition parsing (`f(x, y) = ...`), an invalid token where a parameter name was expected. */\n USER_FUNCTION_INVALID_PARAM_NAME: \"USER_FUNCTION_INVALID_PARAM_NAME\",\n /** `f() = ...` with zero parameters, indistinguishable from a plain no-arg function call, so rejected at definition time. */\n USER_FUNCTION_NO_PARAMS: \"USER_FUNCTION_NO_PARAMS\",\n /** A user-defined function body calling an async plugin (weather/stocks/currency/...), rejected at definition time; v1 scope excludes async function bodies. */\n FUNCTION_BODY_MUST_BE_SYNCHRONOUS: \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n /** `BytecodeBuilder`'s `userFunctionBodies` side-table exceeding its capacity. Same class as `TOO_MANY_NUMERIC_CONSTANTS`/`TOO_MANY_STRING_CONSTANTS` below. */\n TOO_MANY_FUNCTION_DEFINITIONS: \"TOO_MANY_FUNCTION_DEFINITIONS\",\n /** `BytecodeBuilder`'s `anonymousBodies` side-table (map/reduce inline transform bodies) exceeding its capacity. Same class as `TOO_MANY_FUNCTION_DEFINITIONS` above. */\n TOO_MANY_ANONYMOUS_BODIES: \"TOO_MANY_ANONYMOUS_BODIES\",\n /** New with the 2.0 descriptor redesign: a parselet emits a plugin call by NAME (`BytecodeBuilder.emitPluginCall(name, argCount)`) and the engine resolves that name to the index it assigned at registration. This fires when the name is absent from the builder's name->index map: the package used a `pluginFunctions` name it never declared, or the expression was parsed before that package registered. Not a user-input error; a package-authoring/registration fault. See `parser/BytecodeBuilder.ts`'s `emitPluginCall()`. */\n UNKNOWN_PLUGIN_FUNCTION: \"UNKNOWN_PLUGIN_FUNCTION\",\n\n // ── VM (vm/VM.ts, vm/OpRegistry.ts, vm/VMBuiltins.ts) ──\n EVALUATION_ERROR: \"EVALUATION_ERROR\",\n INSTRUCTION_LIMIT_EXCEEDED: \"INSTRUCTION_LIMIT_EXCEEDED\",\n STACK_LIMIT_EXCEEDED: \"STACK_LIMIT_EXCEEDED\",\n /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */\n ALLOCATION_LIMIT_EXCEEDED: \"ALLOCATION_LIMIT_EXCEEDED\",\n /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */\n STACK_UNDERFLOW: \"STACK_UNDERFLOW\",\n UNDEFINED_VARIABLE: \"UNDEFINED_VARIABLE\",\n /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */\n GLOBAL_VARIABLE_NOT_RESOLVED: \"GLOBAL_VARIABLE_NOT_RESOLVED\",\n UNKNOWN_FUNCTION: \"UNKNOWN_FUNCTION\",\n /** `unwrapEvalResult()`'s pending-when-expecting-value case, a caller-contract violation, not user-input. */\n UNEXPECTED_PENDING_RESULT: \"UNEXPECTED_PENDING_RESULT\",\n /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */\n UNDEFINED_FUNCTION: \"UNDEFINED_FUNCTION\",\n FUNCTION_ARITY_MISMATCH: \"FUNCTION_ARITY_MISMATCH\",\n /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */\n BUILTIN_ARITY_MISMATCH: \"BUILTIN_ARITY_MISMATCH\",\n USER_FUNCTION_ASYNC_UNSUPPORTED: \"USER_FUNCTION_ASYNC_UNSUPPORTED\",\n /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */\n MAP_REDUCE_ASYNC_UNSUPPORTED: \"MAP_REDUCE_ASYNC_UNSUPPORTED\",\n /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */\n SYMBOLIC_ASYNC_UNSUPPORTED: \"SYMBOLIC_ASYNC_UNSUPPORTED\",\n /** `explainLine()` asked to derive a line that resolves data asynchronously (a live-data or async-plugin line). A derivation is a sequence of settled intermediate values, which a pending result has none of, so the line is refused rather than explained with a hole in it. */\n EXPLAIN_ASYNC_UNSUPPORTED: \"EXPLAIN_ASYNC_UNSUPPORTED\",\n /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */\n FUNCTION_RECURSION_LIMIT_EXCEEDED: \"FUNCTION_RECURSION_LIMIT_EXCEEDED\",\n /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */\n FUNCTION_CALL_LIMIT_EXCEEDED: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */\n DATE_OFFSET_LIMIT_EXCEEDED: \"DATE_OFFSET_LIMIT_EXCEEDED\",\n /** The anchor of `N working days after/before/from <expr>` was not a date (e.g. `5 working days after 3`). The grammar guarantees the count is a number, so this only fires on the anchor. Emitted as a recoverable Error value, not thrown, matching the datetime package's other type guards. See `vm/VM.ts`'s `DATE_WORKDAY_OFFSET` case. */\n WORKDAY_OFFSET_EXPECTED_DATE: \"WORKDAY_OFFSET_EXPECTED_DATE\",\n /** An endpoint of `working days between <expr> and <expr>` was not a date. Recoverable Error value. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_EXPECTED_DATES: \"WORKDAYS_BETWEEN_EXPECTED_DATES\",\n /** The two endpoints of `working days between <expr> and <expr>` are further apart than `date.maxOffsetYears`/`minOffsetYears` allow the count's calendar walk to run. Recoverable Error value, the between-count's equivalent of `DATE_OFFSET_LIMIT_EXCEEDED`. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_RANGE_TOO_LARGE: \"WORKDAYS_BETWEEN_RANGE_TOO_LARGE\",\n /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */\n BIGINT_SHIFT_LIMIT_EXCEEDED: \"BIGINT_SHIFT_LIMIT_EXCEEDED\",\n /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */\n BIGINT_POW_LIMIT_EXCEEDED: \"BIGINT_POW_LIMIT_EXCEEDED\",\n /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */\n BIGINT_INEXACT_OPERAND: \"BIGINT_INEXACT_OPERAND\",\n /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */\n BIGINT_DIVISION_BY_ZERO: \"BIGINT_DIVISION_BY_ZERO\",\n /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */\n INTERNAL_MISSING_FUNCTION_BODY: \"INTERNAL_MISSING_FUNCTION_BODY\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */\n INTERNAL_MISSING_ANONYMOUS_BODY: \"INTERNAL_MISSING_ANONYMOUS_BODY\",\n /** `CALL_BUILTIN` naming an index no builtin is registered at. It used to pop its arguments and push nothing, so the opcode after it read a neighbour's operand as its own; now an Error value on the stack, the shape `map`/`reduce` already used for the same fault. Bytecode-level, so unreachable from source without a compiler or snapshot fault. */\n UNKNOWN_BUILTIN_FUNCTION: \"UNKNOWN_BUILTIN_FUNCTION\",\n\n // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──\n //\n // `executeBytecode` is exported, so a bytecode program is caller input in\n // the same sense an expression string is, and these five say so. They are\n // VALIDATION rather than INTERNAL for exactly that reason: before they\n // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,\n // `code.toUpperCase()` on a boolean, destructuring a program that was not\n // there), which normalised to UNEXPECTED_ERROR and told the caller the\n // engine was broken when their eleven bytes were. Reachable from ordinary\n // source only through a compiler bug, which is why the messages name the\n // opcode and the operand rather than the user's line.\n /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */\n MALFORMED_BYTECODE_TRUNCATED: \"MALFORMED_BYTECODE_TRUNCATED\",\n /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */\n MALFORMED_BYTECODE_CONSTANT_INDEX: \"MALFORMED_BYTECODE_CONSTANT_INDEX\",\n /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */\n MALFORMED_BYTECODE_OPERAND_TYPE: \"MALFORMED_BYTECODE_OPERAND_TYPE\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */\n MALFORMED_BYTECODE_BODY_KIND: \"MALFORMED_BYTECODE_BODY_KIND\",\n /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `\"1.000\"`. `BigInt()` answers that with a raw SyntaxError. */\n MALFORMED_BYTECODE_BIGINT_LITERAL: \"MALFORMED_BYTECODE_BIGINT_LITERAL\",\n /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */\n MALFORMED_BYTECODE_PROGRAM: \"MALFORMED_BYTECODE_PROGRAM\",\n\n // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──\n /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */\n SYMBOLIC_RATIONAL_OVERFLOW: \"SYMBOLIC_RATIONAL_OVERFLOW\",\n /** `NaN` or `±Infinity` reaching a symbolic expression, neither of which has an exact rational value. */\n SYMBOLIC_NONFINITE_OPERAND: \"SYMBOLIC_NONFINITE_OPERAND\",\n /** Division by an exactly-zero rational. Exact, unlike the double comparison it replaced, which could not distinguish a true zero from `5.551e-17`. */\n SYMBOLIC_DIVISION_BY_ZERO: \"SYMBOLIC_DIVISION_BY_ZERO\",\n /** A tree exceeding `SYMBOLIC_MAX_NODES` entering the simplifier. */\n SYMBOLIC_NODE_LIMIT_EXCEEDED: \"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n /** A builtin with no symbolic reading (`min`, `random`, the finance block, ...) applied to an expression still containing an unknown. Returned rather than computing against `toNumber()`'s placeholder zero. */\n SYMBOLIC_UNSUPPORTED_FUNCTION: \"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n /** The rational-root search exceeding `FACTOR_MAX_ROOT_CANDIDATES`. The candidate set is the product of two divisor sets, so a highly-composite coefficient escapes quickly. */\n SYMBOLIC_FACTOR_LIMIT_EXCEEDED: \"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */\n SYMBOLIC_SOLVE_UNSUPPORTED: \"SYMBOLIC_SOLVE_UNSUPPORTED\",\n /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */\n SYMBOLIC_SOLVE_INCOMPLETE: \"SYMBOLIC_SOLVE_INCOMPLETE\",\n /** `solve`'s second argument not being a bare name. */\n SOLVE_REQUIRES_VARIABLE_NAME: \"SOLVE_REQUIRES_VARIABLE_NAME\",\n /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */\n SYMBOLIC_DERIVATIVE_ORDER_LIMIT: \"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n /** An expression with no known elementary antiderivative. Reported rather than approximated, since a wrong integral is indistinguishable from a right one at the point of use. */\n SYMBOLIC_INTEGRAL_UNSUPPORTED: \"SYMBOLIC_INTEGRAL_UNSUPPORTED\",\n /** A Taylor degree outside 0..`TAYLOR_MAX_DEGREE`. */\n SYMBOLIC_TAYLOR_DEGREE_LIMIT: \"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n /** A Taylor coefficient that does not reduce to an exact number at the expansion point. */\n SYMBOLIC_TAYLOR_INEXACT: \"SYMBOLIC_TAYLOR_INEXACT\",\n /** An algebra verb's variable-name argument not being a bare name. */\n SYMBOLIC_REQUIRES_VARIABLE_NAME: \"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n /** `jacobian` called with expressions containing no unknown to differentiate against. */\n SYMBOLIC_JACOBIAN_NO_VARIABLES: \"SYMBOLIC_JACOBIAN_NO_VARIABLES\",\n /** A finite number whose decimal form could not be read back, which the regex covering every `Number.prototype.toString` output should make unreachable. */\n INTERNAL_RATIONAL_PARSE: \"INTERNAL_RATIONAL_PARSE\",\n\n // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──\n EXPRESSION_TOO_LONG: \"EXPRESSION_TOO_LONG\",\n EXPRESSION_TOO_COMPLEX: \"EXPRESSION_TOO_COMPLEX\",\n /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */\n DOCUMENT_TOO_LARGE: \"DOCUMENT_TOO_LARGE\",\n NORMALIZED_TOKEN_LIMIT_EXCEEDED: \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n /** `\"=>\"` with nothing before it, needs an expression or variable name to solve/simplify. */\n THEREFORE_REQUIRES_EXPRESSION: \"THEREFORE_REQUIRES_EXPRESSION\",\n /** A `\"=>\"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */\n THEREFORE_ASYNC_UNSUPPORTED: \"THEREFORE_ASYNC_UNSUPPORTED\",\n /** A compound assignment (`name += expr` / `name -= expr`) with nothing on the right, a line half-typed on the way to `total += 5`. */\n COMPOUND_ASSIGN_REQUIRES_EXPRESSION: \"COMPOUND_ASSIGN_REQUIRES_EXPRESSION\",\n /** A running total (`+= / -=`) whose right-hand side calls an async plugin (weather/stocks/currency). The same v1 scope restriction as the `\"=>\"` and user-function bodies. */\n COMPOUND_ASSIGN_ASYNC_UNSUPPORTED: \"COMPOUND_ASSIGN_ASYNC_UNSUPPORTED\",\n /** A savings-goal contribution period that is not one of daily/weekly/monthly/yearly (`how long to save $X at $Y <period>`). Names the accepted set. */\n UNKNOWN_SAVINGS_PERIOD: \"UNKNOWN_SAVINGS_PERIOD\",\n /** Colon-separated numbers that are not a time any clock can show (\"24:00\", \"9:60\", \"100:5\"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */\n INVALID_TIME_LITERAL: \"INVALID_TIME_LITERAL\",\n /** A live-data form evaluated on an engine whose host switched the network off (`network.enabled: false`, see `constants/Configuration.ts`'s `NetworkConfig`). A recoverable Error value, raised by the VM for a currency conversion with no primed rate and for a plugin function that returned a promise, and by `createQueryResolver`'s plugin function when its preflight was skipped. Names the setting, so the reader knows it is policy rather than an outage. */\n NETWORK_DISABLED: \"NETWORK_DISABLED\",\n\n // ── Temporal calendar backend (temporal/TemporalCalendar.ts) ──\n /** `createTemporalCalendar()` was handed something that is not a usable `Temporal` implementation: no `Now.instant`, `Now.timeZoneId`, `Instant.fromEpochMilliseconds` or `PlainDateTime.from`. Raised at construction, naming the missing member, rather than letting the first date computation fail on it obscurely. */\n TEMPORAL_IMPLEMENTATION_INVALID: \"TEMPORAL_IMPLEMENTATION_INVALID\",\n /** The `timeZone` given to `createTemporalCalendar()` is not one the `Temporal` implementation knows. Raised at construction, so a misspelt zone is a configuration error the host sees once, not a `RangeError` from inside every date the engine computes. */\n TEMPORAL_TIME_ZONE_UNKNOWN: \"TEMPORAL_TIME_ZONE_UNKNOWN\",\n\n // ── Snapshot / restore (engine/EngineSnapshot.ts, engine/ExpressionEngine.ts) ──\n /** `fromJSON()` handed an object that is not a snapshot at all, or whose serialised-shape version does not match this engine's reader. The versioning gate that refuses an incompatible snapshot clearly rather than restoring it wrongly. See `engine/EngineSnapshot.ts`'s `assertRestorable()`. */\n SNAPSHOT_VERSION_MISMATCH: \"SNAPSHOT_VERSION_MISMATCH\",\n /** A snapshot with the right envelope but internally inconsistent contents (an unrecognised number sentinel, an unknown value tag). Distinct from a version mismatch: the format is right, the payload is not. */\n SNAPSHOT_MALFORMED: \"SNAPSHOT_MALFORMED\",\n /** A value the v1 snapshot format cannot yet represent (a symbolic/algebra value, a symbolic matrix cell). Deferred to a follow-up; refused by name rather than dropped silently. */\n SNAPSHOT_UNSUPPORTED_VALUE: \"SNAPSHOT_UNSUPPORTED_VALUE\",\n\n // ── Config (constants/Configuration.ts) ──\n CONFIG_PATH_NOT_FOUND: \"CONFIG_PATH_NOT_FOUND\",\n INVALID_CONFIG_PATH: \"INVALID_CONFIG_PATH\",\n CONFIG_SECTION_NOT_FOUND: \"CONFIG_SECTION_NOT_FOUND\",\n CONFIG_PROPERTY_NOT_FOUND: \"CONFIG_PROPERTY_NOT_FOUND\",\n\n // ── Package/lexer registration-time collisions (lexer/ExpressionLexer.ts) ──\n /** `calendar: \"temporal\"` was asked for on a runtime with no `Temporal`. Refused rather than silently computing on `Date`, because a host that named Temporal did so to be sure what it was computing on. Recoverable. */\n CALENDAR_TEMPORAL_UNAVAILABLE: \"CALENDAR_TEMPORAL_UNAVAILABLE\",\n /** A trip form (`cost to drive ...`) was written without the `at` that separates its parts. Recoverable. */\n TRIP_EXPECTED_AT: \"TRIP_EXPECTED_AT\",\n PLUGIN_OPERATOR_COLLISION: \"PLUGIN_OPERATOR_COLLISION\",\n PLUGIN_KEYWORD_COLLISION: \"PLUGIN_KEYWORD_COLLISION\",\n PLUGIN_UNIT_COLLISION: \"PLUGIN_UNIT_COLLISION\",\n /** A package's declared `IEnginePackage.engineVersion` semver range doesn't satisfy the running engine's ENGINE_VERSION. See api/EngineVersionCompatibility.ts. */\n PACKAGE_ENGINE_VERSION_MISMATCH: \"PACKAGE_ENGINE_VERSION_MISMATCH\",\n /** A package's declared `IEnginePackage.engineVersion` isn't a parseable semver range at all (a typo in the package's own descriptor). */\n PACKAGE_ENGINE_VERSION_INVALID_RANGE: \"PACKAGE_ENGINE_VERSION_INVALID_RANGE\",\n /** `OpRegistry.allocateOpcode()`'s dynamic opcode pool (started at 201) exhausted, too many packages calling it. */\n OPCODE_POOL_EXHAUSTED: \"OPCODE_POOL_EXHAUSTED\",\n /** `VMBuiltins.allocatePluginFunctionIndex()`'s index pool (up to 65536, two opcode-stream bytes) exhausted. */\n PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED: \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n /** A plugin-function index exceeds the two-byte (65535) `CALL_PLUGIN_WIDE` bytecode operand. */\n PLUGIN_FUNCTION_INDEX_TOO_LARGE: \"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\n // ── vm/Value.ts caller-contract violations (check isRateUnit()/isTimecodeUnit() first) ──\n INVALID_RATE_UNIT: \"INVALID_RATE_UNIT\",\n INVALID_TIMECODE_UNIT: \"INVALID_TIMECODE_UNIT\",\n\n // ── errors/EngineError.ts's own fallback normalization ──\n UNEXPECTED_ERROR: \"UNEXPECTED_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\n/** Every error code the engine's own layers can produce, from {@link CoreErrorCodes}. */\nexport type CoreErrorCode = (typeof CoreErrorCodes)[keyof typeof CoreErrorCodes];\n\n/**\n * Codes for the datetime forms whose failure is raised OUTSIDE the datetime\n * package.\n *\n * These sit here rather than beside the datetime parselets, which is where a\n * package's own code object belongs, because the two sites that raise them are\n * `vm/VM.ts` (the `in <zone>` branch of the unit-conversion opcode) and\n * `calendar/DateCalendar.ts` (the zone-bound backend factory), and neither may\n * import from `packages/`. A code object in the datetime package would put the\n * name a core file needs on the wrong side of that line.\n */\nexport const DatetimeErrorCodes = {\n /** `2026-04-03 in Atlantis`: a Datetime met `in <name>` and the name is neither a zone this engine knows nor a unit. Before this code the epoch-millisecond payload was simply labelled with the name, and the line answered a fourteen-digit quantity in a unit called Atlantis. */\n DATETIME_ZONE_UNKNOWN: \"DATETIME_ZONE_UNKNOWN\",\n /** `2026-04-03 in furlongs`: the same handler, where the name IS a real unit. Separate from `DATETIME_ZONE_UNKNOWN` because the two mistakes have different fixes: one is a misspelt zone, the other is a category error, and a message that suggests checking the spelling of `furlongs` would be no help at all. */\n DATETIME_NOT_CONVERTIBLE: \"DATETIME_NOT_CONVERTIBLE\",\n /** `dateCalendarInZone(\"Europe/Atlantis\")`: the zone-bound `Date` backend factory, given a zone this runtime's `Intl` cannot format with. Raised at construction rather than per line, because a backend that cannot compute in the zone it was asked for must not silently answer in another one. */\n DATE_ZONE_UNKNOWN: \"DATE_ZONE_UNKNOWN\",\n} as const;\n\n/** Every code from {@link DatetimeErrorCodes}. */\nexport type DatetimeErrorCode = (typeof DatetimeErrorCodes)[keyof typeof DatetimeErrorCodes];\n\n/**\n * The aggregated catalog type. Currently `CoreErrorCode` and\n * `DatetimeErrorCode`, union in each package's own code-object type here as\n * Phase 5 converts it, e.g. `CoreErrorCode | WeatherErrorCode | ...`.\n */\nexport type ErrorCode = CoreErrorCode | DatetimeErrorCode;\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b,m,n}from'./chunk-J4K72CQN.js';import {c,r}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {b,m,n}from'./chunk-J4K72CQN.js';import {c,r}from'./chunk-Z5DA5UXY.js';function x(m,n,e){let r=Math.trunc(m),o=Math.trunc(n),a=Math.trunc(e);if(!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(a))return Number.NaN;let t=r+Math.floor(o/12),i=(o%12+12)%12+1,s=t-(i<=2?1:0),l=Math.floor(s/400),u=s-l*400,N=Math.floor((153*(i+(i>2?-3:9))+2)/5),c=u*365+Math.floor(u/4)-Math.floor(u/100)+N;return l*146097+c-719468+(a-1)}function F(m){if(!Number.isFinite(m))return {year:Number.NaN,month0:Number.NaN,day:Number.NaN};let n=Math.trunc(m)+719468,e=Math.floor(n/146097),r=n-e*146097,o=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),a=r-(365*o+Math.floor(o/4)-Math.floor(o/100)),t=Math.floor((5*a+2)/153),i=a-Math.floor((153*t+2)/5)+1,s=t<10?t+3:t-9;return {year:o+e*400+(s<=2?1:0),month0:s-1,day:i}}var P=Object.freeze({year:Number.NaN,month0:Number.NaN,day:Number.NaN,weekday:Number.NaN,hour:Number.NaN,minute:Number.NaN,second:Number.NaN,millisecond:Number.NaN}),Z=864e13,d=864e5;function D(m){return !Number.isFinite(m)||Math.abs(m)>Z?Number.NaN:Math.trunc(m)}function z(m,n,e,r,o,a,t){let i=Math.trunc(r)*36e5+Math.trunc(o)*6e4+Math.trunc(a)*1e3+Math.trunc(t);return {dayNumber:x(m,n,e)+Math.floor(i/d),timeOfDay:(i%d+d)%d}}var S=/^([+-]\d{6}|\d{4})(?:-(\d{2})(?:-(\d{2}))?)?(?:[Tt](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,k=class{constructor(n,e={}){A(n),this.temporal=n;let r$1=e.timeZone??n.Now.timeZoneId(),o;try{o=n.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(r$1);}catch(a){throw c.config(r.TEMPORAL_TIME_ZONE_UNKNOWN,`The Temporal implementation does not know the time zone "${r$1}"`,{timeZone:r$1,cause:a instanceof Error?a.message:String(a)})}this.timeZone=o.timeZoneId,this.clock=e.now??(()=>n.Now.instant().epochMilliseconds);}now(){return this.clock()}fields(n){let e=this.zoned(n,this.timeZone);return e===null?P:{year:e.year,month0:e.month-1,day:e.day,weekday:e.dayOfWeek%7,hour:e.hour,minute:e.minute,second:e.second,millisecond:e.millisecond}}localMidnight(n,e,r){return this.wallClock(n,e,r,0,0,0,0)}localWallClock(n,e,r,o){let a=this.localMidnight(n,e,r),t=this.fields(a);return Number.isNaN(t.year)?Number.NaN:this.wallClock(t.year,t.month0,t.day,t.hour,o,t.second,t.millisecond)}addDays(n,e){let r=this.fields(n);return Number.isNaN(r.year)?Number.NaN:this.wallClock(r.year,r.month0,r.day+e,r.hour,r.minute,r.second,r.millisecond)}addMonths(n,e){let r=this.fields(n);if(Number.isNaN(r.year))return Number.NaN;let o=r.day,a=this.fields(this.wallClock(r.year,r.month0,1,r.hour,r.minute,r.second,r.millisecond));if(Number.isNaN(a.year))return Number.NaN;let t=this.fields(this.wallClock(a.year,a.month0+e,a.day,a.hour,a.minute,a.second,a.millisecond));if(Number.isNaN(t.year))return Number.NaN;let i=Math.min(o,b(t.year,t.month0));return this.wallClock(t.year,t.month0,i,t.hour,t.minute,t.second,t.millisecond)}utcOffsetMinutes(n){let e=this.zoned(n,this.timeZone);return e===null?Number.NaN:Math.trunc(e.offsetNanoseconds/6e10)||0}parseIso8601(n){let e=S.exec(n);if(e===null)return Number.NaN;let[,r,o,a,t,i,s,l,u]=e;if(r==="-000000")return Number.NaN;let N=Number(r),c=o===void 0?1:Number(o),f=a===void 0?1:Number(a),b=t===void 0?0:Number(t),h=i===void 0?0:Number(i),y=s===void 0?0:Number(s),I=l===void 0?0:Number(l.slice(0,3).padEnd(3,"0"));if(c<1||c>12||f<1||f>31||b>24||h>59||y>59||b===24&&(h!==0||y!==0||I!==0))return Number.NaN;let p=z(N,c-1,f,b,h,y,I);if(u===void 0&&t!==void 0)return this.resolve(p);let g=0;if(u!==void 0&&u!=="Z"&&u!=="z"){let _=u.slice(1).replace(":",""),w=Number(_.slice(0,2)),C=Number(_.slice(2,4));if(w>23||C>59)return Number.NaN;g=(u[0]==="-"?-1:1)*(w*60+C);}let O=p.dayNumber*d+p.timeOfDay-g*6e4;return Math.abs(O)>Z?Number.NaN:O}formatLongDate(n,e){let r=D(n);return Number.isNaN(r)?"Invalid Date":new Intl.DateTimeFormat(e,{timeZone:this.timeZone,weekday:"long",year:"numeric",month:"long",day:"numeric"}).format(r)}formatTimeOfDay(n,e){let r=D(n);return Number.isNaN(r)?"Invalid Date":new Intl.DateTimeFormat(e,{timeZone:this.timeZone,hour:"numeric",minute:"numeric",second:"numeric"}).format(r)}zoneOffsetMinutes(n,e){let r=Number.isFinite(e)?Math.trunc(e):e,o=this.temporal.Instant.fromEpochMilliseconds(r).toZonedDateTimeISO(n),a=Math.floor((r+o.offsetNanoseconds/1e6)/1e3)*1e3;return Math.round((a-e)/6e4)||0}fieldsInZone(n,e){let r=Number.isFinite(e)?Math.trunc(e):e,o=this.temporal.Instant.fromEpochMilliseconds(r).toZonedDateTimeISO(n);return {year:o.year,month0:o.month-1,day:o.day,hour:o.hour,minute:o.minute,second:o.second}}zone(){return this.timeZone}formatTimeInZone(n,e){return m(n,e)}formatDateInZone(n$1,e){return n(n$1,e)}zoned(n,e){let r=D(n);if(Number.isNaN(r))return null;try{return this.temporal.Instant.fromEpochMilliseconds(r).toZonedDateTimeISO(e)}catch{return null}}wallClock(n,e,r,o,a,t,i){let s=n>=0&&n<=99?1900+Math.trunc(n):n;return this.resolve(z(s,e,r,o,a,t,i))}resolve(n){let e=F(n.dayNumber);if(Number.isNaN(e.year))return Number.NaN;let r=Math.floor(n.timeOfDay/36e5),o=Math.floor(n.timeOfDay/6e4)%60,a=Math.floor(n.timeOfDay/1e3)%60,t=n.timeOfDay%1e3;try{let s=this.temporal.PlainDateTime.from({year:e.year,month:e.month0+1,day:e.day,hour:r,minute:o,second:a,millisecond:t},{overflow:"reject"}).toZonedDateTime(this.timeZone,{disambiguation:"compatible"}).epochMilliseconds;return Math.abs(s)>Z?Number.NaN:s}catch{return Number.NaN}}};function A(m){let n=m,e=typeof n?.Now?.instant!="function"?"Now.instant":typeof n?.Now?.timeZoneId!="function"?"Now.timeZoneId":typeof n?.Instant?.fromEpochMilliseconds!="function"?"Instant.fromEpochMilliseconds":typeof n?.PlainDateTime?.from!="function"?"PlainDateTime.from":null;if(e!==null)throw c.config(r.TEMPORAL_IMPLEMENTATION_INVALID,`createTemporalCalendar needs a Temporal implementation (globalThis.Temporal on a runtime that ships it, or a polyfill's export); the value given has no ${e}`,{missing:e})}function q(m,n={}){return new k(m,n)}export{k as a,q as b};//# sourceMappingURL=chunk-I6WGOM3C.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-I6WGOM3C.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/temporal/CivilDays.ts","../src/temporal/TemporalCalendar.ts"],"names":["civilDayNumber","year","month0","day","y0","m0","d","y","m","shiftedYear","era","yearOfEra","dayOfYear","dayOfEra","civilFromDayNumber","days","z","monthFromMarch","month","NAN_FIELDS","MAX_INSTANT","MS_PER_DAY","clip","epochMs","normaliseWallClock","hour","minute","second","millisecond","time","ISO_DATE_TIME","TemporalCalendar","temporal","options","assertTemporalLike","requested","probe","error","ErrorFactory","CoreErrorCodes","minutesPastMidnight","anchored","a","f","months","f0","dayOfMonth","f1","f2","daysInMonth","text","yearText","monthText","dayText","hourText","minuteText","secondText","fractionText","zoneText","wall","offsetMinutes","digits","offsetHours","offsetMinutesPart","instant","locale","t","zone","wallSecond","timeInZone","dateInZone","windowed","civil","candidate","missing","createTemporalCalendar"],"mappings":"8EAkDO,SAASA,EAAeC,CAAAA,CAAcC,CAAAA,CAAgBC,CAAAA,CAAqB,CACjF,IAAMC,CAAAA,CAA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AClBC,CAAAA,CAAe,gCACf,CAAA,wJAAA,EAA2JmC,CAAO,CAAA,CAAA,CAClK,CAAE,QAAAA,CAAQ,CACX,CAEF,CAoBO,SAASC,CAAAA,CAAuB3C,CAAAA,CAAwBC,CAAAA,CAAmC,GAAsB,CACvH,OAAO,IAAIF,CAAAA,CAAiBC,CAAAA,CAAUC,CAAO,CAC9C","file":"chunk-D4VBWPWN.js","sourcesContent":["/**\n * The day arithmetic behind `Date`'s field normalisation, for the `Temporal`\n * backend.\n *\n * `Date` normalises a set of wall-clock fields before it resolves them in a\n * zone: month 13 rolls into the next year, day 0 into the month before, a\n * time past midnight into the next day, and only the final instant is\n * clipped to the range `Date` represents. That is the `MakeDay` and\n * `MakeTime` order of the ECMAScript specification, and a backend built on\n * another library has to follow it to answer what `Date` answers on the last\n * representable day and for a rolled-over literal. `Date` does this\n * arithmetic inside its own setters, where a second backend cannot reach it,\n * so it is written out here with nothing clipped.\n *\n * Under `temporal/` rather than `calendar/Gregorian.ts` because only the\n * `Temporal` backend needs it: the `Date` backend gets the same arithmetic\n * from `Date` itself, and keeping it here keeps it out of the root entry's\n * bundle. The unit spec measures it against `Date.UTC` and `setUTCFullYear`\n * wherever `Date` can represent the date.\n *\n * @module CivilDays\n */\n\n/** A calendar date as year, zero-based month and day, the shape the civil-day arithmetic exchanges. */\nexport interface CivilDate {\n\treadonly year: number;\n\t/** Zero-based month: 0 is January, 11 is December. */\n\treadonly month0: number;\n\t/** Day of the month, from 1. */\n\treadonly day: number;\n}\n\n/**\n * The day number of a calendar date, counted from 1 January 1970, by\n * arithmetic alone: no `Date`, so no clip to the range `Date` represents.\n *\n * This is the `MakeDay` step of the ECMAScript specification, which a\n * backend needs unclipped: `Date` normalises a set of fields (month 13, day\n * 0, a time past midnight) before it resolves them in a zone and clips the\n * result, so a wall-clock time on the last representable day is an instant,\n * not `NaN`, and a backend built on another library must follow the same\n * order. An overflowing month or day rolls into the adjacent year or month,\n * as {@link utcMs}'s do, and a fractional field is truncated, as `Date`\n * truncates it.\n *\n * @param year - The calendar year, read as written.\n * @param month0 - Zero-based month; overflow rolls into the adjacent year.\n * @param day - Day of the month; overflow rolls into the adjacent month.\n * @returns Whole days since 1 January 1970, negative before it, or `NaN` when a field is not finite.\n */\nexport function civilDayNumber(year: number, month0: number, day: number): number {\n\tconst y0 = Math.trunc(year);\n\tconst m0 = Math.trunc(month0);\n\tconst d = Math.trunc(day);\n\tif (!Number.isFinite(y0) || !Number.isFinite(m0) || !Number.isFinite(d)) return Number.NaN;\n\t// Normalise the month into the year first, then count from the first of\n\t// that month, so a day of 0 or 40 is a plain offset from a real month.\n\tconst y = y0 + Math.floor(m0 / 12);\n\tconst m = ((m0 % 12) + 12) % 12 + 1;\n\t// The days-from-civil arithmetic, with the year taken to start in March\n\t// so a leap day is the last day of the cycle rather than an exception.\n\tconst shiftedYear = y - (m <= 2 ? 1 : 0);\n\tconst era = Math.floor(shiftedYear / 400);\n\tconst yearOfEra = shiftedYear - era * 400;\n\tconst dayOfYear = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5);\n\tconst dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;\n\treturn era * 146_097 + dayOfEra - 719_468 + (d - 1);\n}\n\n/**\n * The calendar date of a day number, the inverse of {@link civilDayNumber}.\n *\n * @param days - Whole days since 1 January 1970, negative before it.\n * @returns The date, or `NaN` in every field when `days` is not finite.\n */\nexport function civilFromDayNumber(days: number): CivilDate {\n\tif (!Number.isFinite(days)) return { year: Number.NaN, month0: Number.NaN, day: Number.NaN };\n\tconst z = Math.trunc(days) + 719_468;\n\tconst era = Math.floor(z / 146_097);\n\tconst dayOfEra = z - era * 146_097;\n\tconst yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36_524) - Math.floor(dayOfEra / 146_096)) / 365);\n\tconst dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));\n\tconst monthFromMarch = Math.floor((5 * dayOfYear + 2) / 153);\n\tconst day = dayOfYear - Math.floor((153 * monthFromMarch + 2) / 5) + 1;\n\tconst month = monthFromMarch < 10 ? monthFromMarch + 3 : monthFromMarch - 9;\n\tconst year = yearOfEra + era * 400 + (month <= 2 ? 1 : 0);\n\treturn { year, month0: month - 1, day };\n}\n","/**\n * The `Temporal` calendar backend: the engine's date questions answered\n * through a `Temporal` implementation the host supplies, in a time zone the\n * host chooses.\n *\n * `Temporal` is the JavaScript standard library's replacement for `Date`. It\n * ships unflagged in Node 26 and in current Chrome, Firefox and Deno, but not\n * in Safari nor in Node 22 and 24, and the smallest polyfill adds about twenty\n * kilobytes gzipped to a bundle. The engine therefore imports no `Temporal`\n * and no polyfill: this module is reached only through the\n * `solve-engine/temporal` entry, and the host hands it the implementation to\n * use, `globalThis.Temporal` on a runtime that has one or a polyfill's export.\n * A host that never imports the entry pays nothing for it.\n *\n * The backend answers exactly what the `Date` backend answers. That is a\n * design constraint rather than a hope: `Temporal` and `Date` differ in what\n * they do with an out-of-range instant (`RangeError` against `NaN`), a\n * fractional millisecond (a throw against truncation), a day past the end of\n * a month (a clamp or a throw against a roll into the next month) and a year\n * from 0 to 99 (read literally against read as the 1900s), and every one of\n * those is reproduced here the way `Date` does it, because the engine's\n * results are measured against `Date` and a host switching backends must see\n * no result move. The differential suite under `__tests__/temporal/` is what\n * holds that line.\n *\n * The one thing that does change is the zone. `Date` reads the process's own\n * zone and nothing else; this backend reads the zone it was constructed with,\n * so a document can be computed in Tokyo from a server in London, or in a\n * zone the reader picks. That is the capability the backend adds, and the\n * only observable difference.\n *\n * The named-zone display strings go through the same `Intl.DateTimeFormat`\n * helpers the `Date` backend uses (`calendar/IntlZone.ts`), and the zone-free\n * arithmetic through `calendar/Gregorian.ts`, so the two backends share one\n * implementation wherever an answer does not depend on which backend is in\n * use. The one piece of arithmetic `Date` keeps inside its own setters, the\n * normalisation of overflowing fields, is written out in `CivilDays.ts`.\n *\n * @module TemporalCalendar\n */\n\nimport type { CalendarBackend, CalendarFields, ZonedFields } from \"@solve-js/calendar/CalendarBackend\";\nimport { daysInMonth } from \"@solve-js/calendar/Gregorian\";\nimport { civilDayNumber, civilFromDayNumber } from \"./CivilDays\";\nimport { dateInZone, timeInZone } from \"@solve-js/calendar/IntlZone\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { CoreErrorCodes } from \"@solve-js/errors/ErrorCode\";\n\n/**\n * The part of a `Temporal.Instant` the backend reads: its epoch milliseconds,\n * and the zoned date-time it shows in a named zone.\n */\nexport interface TemporalInstantLike {\n\treadonly epochMilliseconds: number;\n\ttoZonedDateTimeISO(timeZone: string): TemporalZonedDateTimeLike;\n}\n\n/**\n * The part of a `Temporal.ZonedDateTime` the backend reads: the calendar\n * fields (a one-based month and an ISO weekday, Monday 1 to Sunday 7, both\n * translated at the boundary), the offset, and the instant.\n */\nexport interface TemporalZonedDateTimeLike {\n\treadonly year: number;\n\t/** One-based month, 1 is January, as `Temporal` counts. */\n\treadonly month: number;\n\treadonly day: number;\n\t/** ISO weekday: Monday is 1, Sunday is 7. */\n\treadonly dayOfWeek: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly second: number;\n\treadonly millisecond: number;\n\t/** The zone's offset from UTC at this instant, in nanoseconds, positive when ahead. */\n\treadonly offsetNanoseconds: number;\n\treadonly epochMilliseconds: number;\n\t/** The zone's canonical IANA identifier. */\n\treadonly timeZoneId: string;\n}\n\n/** The part of a `Temporal.PlainDateTime` the backend uses: resolving a wall-clock time to an instant in a zone. */\nexport interface TemporalPlainDateTimeLike {\n\ttoZonedDateTime(\n\t\ttimeZone: string,\n\t\toptions?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" },\n\t): TemporalZonedDateTimeLike;\n}\n\n/** The wall-clock fields a `Temporal.PlainDateTime` is built from, with a one-based month. */\nexport interface TemporalDateTimeFields {\n\tyear: number;\n\t/** One-based month, 1 is January. */\n\tmonth: number;\n\tday: number;\n\thour: number;\n\tminute: number;\n\tsecond: number;\n\tmillisecond: number;\n}\n\n/**\n * The subset of the `Temporal` namespace the backend uses, as a structural\n * type, so the engine compiles and ships with no `Temporal` type installed\n * and a host passes whichever implementation it has: `globalThis.Temporal`\n * on Node 26 or a current browser, or the export of a polyfill such as\n * `temporal-polyfill`. Both satisfy this shape as they are.\n */\nexport interface TemporalLike {\n\treadonly Now: {\n\t\tinstant(): TemporalInstantLike;\n\t\ttimeZoneId(): string;\n\t};\n\treadonly Instant: {\n\t\tfromEpochMilliseconds(epochMilliseconds: number): TemporalInstantLike;\n\t};\n\treadonly PlainDateTime: {\n\t\tfrom(fields: TemporalDateTimeFields, options?: { overflow?: \"constrain\" | \"reject\" }): TemporalPlainDateTimeLike;\n\t};\n}\n\n/** What {@link createTemporalCalendar} takes beside the implementation. */\nexport interface TemporalCalendarOptions {\n\t/**\n\t * The IANA time zone the engine computes dates in (`\"Asia/Tokyo\"`,\n\t * `\"UTC\"`). Defaults to the runtime's own zone, `Temporal.Now.timeZoneId()`,\n\t * which is what the `Date` backend reads. A zone the implementation does\n\t * not know is refused at construction with `TEMPORAL_TIME_ZONE_UNKNOWN`.\n\t */\n\ttimeZone?: string;\n\t/**\n\t * The clock `now()` reads, in epoch milliseconds. Defaults to\n\t * `Temporal.Now.instant()`. A test pins a date with this: a fake-timer\n\t * library replaces `Date.now`, which the `Date` backend reads, but not\n\t * `Temporal.Now`, so this backend needs telling separately.\n\t */\n\tnow?: () => number;\n}\n\n/** The fields the `Date` backend answers for an instant it cannot represent. */\nconst NAN_FIELDS: CalendarFields = Object.freeze({\n\tyear: Number.NaN, month0: Number.NaN, day: Number.NaN, weekday: Number.NaN,\n\thour: Number.NaN, minute: Number.NaN, second: Number.NaN, millisecond: Number.NaN,\n});\n\n/** The largest magnitude `Date` represents, in milliseconds either side of the epoch. */\nconst MAX_INSTANT = 8.64e15;\n\n/** Milliseconds in a day of wall-clock fields, before any zone is consulted. */\nconst MS_PER_DAY = 86_400_000;\n\n/**\n * An instant as `Date` would hold it: truncated to a whole millisecond, or\n * `NaN` when it is not finite or lies past the range `Date` represents. This\n * is `Date`'s own clip (its `TimeClip`), applied before an instant reaches\n * `Temporal`, which throws for both cases where `Date` answers `NaN`.\n */\nfunction clip(epochMs: number): number {\n\tif (!Number.isFinite(epochMs) || Math.abs(epochMs) > MAX_INSTANT) return Number.NaN;\n\treturn Math.trunc(epochMs);\n}\n\n/**\n * Wall-clock fields normalised the way `Date`'s `MakeDay` and `MakeTime`\n * normalise them, with nothing clipped: the day number of the date the\n * fields land on after any overflow rolls, and the time within that day.\n * Each field is truncated to an integer first, as `Date` truncates it.\n */\ninterface WallClock {\n\treadonly dayNumber: number;\n\treadonly timeOfDay: number;\n}\n\n/** `MakeDay` and `MakeTime`, then `MakeDate`, with a time past midnight carried into the day. */\nfunction normaliseWallClock(year: number, month0: number, day: number, hour: number, minute: number, second: number, millisecond: number): WallClock {\n\tconst time = Math.trunc(hour) * 3_600_000 + Math.trunc(minute) * 60_000 + Math.trunc(second) * 1_000 + Math.trunc(millisecond);\n\tconst dayNumber = civilDayNumber(year, month0, day) + Math.floor(time / MS_PER_DAY);\n\treturn { dayNumber, timeOfDay: ((time % MS_PER_DAY) + MS_PER_DAY) % MS_PER_DAY };\n}\n\n/**\n * The ECMAScript date-time string format, as the `Date` constructor reads it:\n * a four-digit or six-digit signed year, an optional month and day, an\n * optional time to the millisecond (longer fractions are truncated), and an\n * optional `Z` or offset. The `T` and `Z` may be lower case, and an offset\n * may omit its colon; both are what the runtime's parser accepts.\n */\nconst ISO_DATE_TIME =\n\t/^([+-]\\d{6}|\\d{4})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:[Tt](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?)?([Zz]|[+-]\\d{2}:?\\d{2})?$/;\n\n/**\n * A {@link CalendarBackend} over a `Temporal` implementation, computing in\n * one named time zone. Build one with {@link createTemporalCalendar}.\n *\n * Every method answers what the `Date` backend answers for the same inputs\n * when the zone is the process's own; see the module comment for the\n * differences between `Temporal` and `Date` that are reproduced deliberately.\n * The local methods answer `NaN` for an instant or a date the backend cannot\n * represent and never throw; the four named-zone methods throw the runtime's\n * `RangeError` for a zone it does not know or an instant it cannot represent,\n * which is the contract the interface states.\n */\nexport class TemporalCalendar implements CalendarBackend {\n\t/** The IANA zone every local answer is computed in, in its canonical spelling. */\n\treadonly timeZone: string;\n\n\tprivate readonly temporal: TemporalLike;\n\tprivate readonly clock: () => number;\n\n\tconstructor(temporal: TemporalLike, options: TemporalCalendarOptions = {}) {\n\t\tassertTemporalLike(temporal);\n\t\tthis.temporal = temporal;\n\t\tconst requested = options.timeZone ?? temporal.Now.timeZoneId();\n\t\tlet probe: TemporalZonedDateTimeLike;\n\t\ttry {\n\t\t\tprobe = temporal.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(requested);\n\t\t} catch (error) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tCoreErrorCodes.TEMPORAL_TIME_ZONE_UNKNOWN,\n\t\t\t\t`The Temporal implementation does not know the time zone \"${requested}\"`,\n\t\t\t\t{ timeZone: requested, cause: error instanceof Error ? error.message : String(error) },\n\t\t\t);\n\t\t}\n\t\t// The canonical spelling, so a zone given as `asia/tokyo` reads back as\n\t\t// the identifier the implementation itself uses.\n\t\tthis.timeZone = probe.timeZoneId;\n\t\tthis.clock = options.now ?? (() => temporal.Now.instant().epochMilliseconds);\n\t}\n\n\tnow(): number {\n\t\treturn this.clock();\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst z = this.zoned(epochMs, this.timeZone);\n\t\tif (z === null) return NAN_FIELDS;\n\t\treturn {\n\t\t\tyear: z.year,\n\t\t\tmonth0: z.month - 1,\n\t\t\tday: z.day,\n\t\t\t// ISO's Monday 1 to Sunday 7 becomes Date's Sunday 0 to Saturday 6.\n\t\t\tweekday: z.dayOfWeek % 7,\n\t\t\thour: z.hour,\n\t\t\tminute: z.minute,\n\t\t\tsecond: z.second,\n\t\t\tmillisecond: z.millisecond,\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn this.wallClock(year, month0, day, 0, 0, 0, 0);\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// `Date`'s sequence exactly: anchor at midnight, then set the minutes\n\t\t// FIELD, which reads the hour, second and millisecond back from the\n\t\t// anchored local time. On a day whose midnight falls in a\n\t\t// daylight-saving gap the anchor resolves to 1 am, and the hour it\n\t\t// reads back is 1, which is what makes the two backends agree there.\n\t\tconst anchored = this.localMidnight(year, month0, day);\n\t\tconst a = this.fields(anchored);\n\t\tif (Number.isNaN(a.year)) return Number.NaN;\n\t\treturn this.wallClock(a.year, a.month0, a.day, a.hour, minutesPastMidnight, a.second, a.millisecond);\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\t// `setDate()`: the day field moves and the local time of day is held.\n\t\tconst f = this.fields(epochMs);\n\t\tif (Number.isNaN(f.year)) return Number.NaN;\n\t\treturn this.wallClock(f.year, f.month0, f.day + days, f.hour, f.minute, f.second, f.millisecond);\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\t// The `Date` backend's three field writes, each resolved to an instant\n\t\t// and read back before the next, so that a wall-clock time landing in\n\t\t// a transition on an intermediate date shifts the same way it does\n\t\t// there: park on the 1st, move the month, then clamp the day.\n\t\tconst f0 = this.fields(epochMs);\n\t\tif (Number.isNaN(f0.year)) return Number.NaN;\n\t\tconst dayOfMonth = f0.day;\n\t\tconst f1 = this.fields(this.wallClock(f0.year, f0.month0, 1, f0.hour, f0.minute, f0.second, f0.millisecond));\n\t\tif (Number.isNaN(f1.year)) return Number.NaN;\n\t\tconst f2 = this.fields(this.wallClock(f1.year, f1.month0 + months, f1.day, f1.hour, f1.minute, f1.second, f1.millisecond));\n\t\tif (Number.isNaN(f2.year)) return Number.NaN;\n\t\tconst day = Math.min(dayOfMonth, daysInMonth(f2.year, f2.month0));\n\t\treturn this.wallClock(f2.year, f2.month0, day, f2.hour, f2.minute, f2.second, f2.millisecond);\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\tconst z = this.zoned(epochMs, this.timeZone);\n\t\tif (z === null) return Number.NaN;\n\t\t// `getTimezoneOffset()` answers whole minutes, truncated toward zero,\n\t\t// which only shows for the local-mean-time offsets in force before a\n\t\t// zone adopted standard time (London's was -00:01:15 until 1847).\n\t\t// `|| 0` folds the -0 a small negative offset truncates to.\n\t\treturn Math.trunc(z.offsetNanoseconds / 60_000_000_000) || 0;\n\t}\n\n\tparseIso8601(text: string): number {\n\t\t// Only the format itself. The `Date` constructor falls back to a\n\t\t// legacy parser for a string the format rejects (one with a space\n\t\t// around it, say) and may guess an instant from it; the engine's own\n\t\t// gate admits only the format, so the two backends cannot disagree\n\t\t// through it, and outside it this backend answers NaN rather than guess.\n\t\tconst m = ISO_DATE_TIME.exec(text);\n\t\tif (m === null) return Number.NaN;\n\t\tconst [, yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, zoneText] = m;\n\t\t// An expanded year of `-000000` names no year, by the format's own rule.\n\t\tif (yearText === \"-000000\") return Number.NaN;\n\t\tconst year = Number(yearText);\n\t\tconst month = monthText === undefined ? 1 : Number(monthText);\n\t\tconst day = dayText === undefined ? 1 : Number(dayText);\n\t\tconst hour = hourText === undefined ? 0 : Number(hourText);\n\t\tconst minute = minuteText === undefined ? 0 : Number(minuteText);\n\t\tconst second = secondText === undefined ? 0 : Number(secondText);\n\t\t// Only the first three digits of a fraction are milliseconds; the rest\n\t\t// are dropped rather than rounded, as the runtime's parser does.\n\t\tconst millisecond = fractionText === undefined ? 0 : Number(fractionText.slice(0, 3).padEnd(3, \"0\"));\n\t\t// The runtime checks a day against 31, not against the month, and lets\n\t\t// 30 February roll into March; 24:00 is the end of the day and nothing\n\t\t// past it is a time.\n\t\tif (month < 1 || month > 12 || day < 1 || day > 31) return Number.NaN;\n\t\tif (hour > 24 || minute > 59 || second > 59) return Number.NaN;\n\t\tif (hour === 24 && (minute !== 0 || second !== 0 || millisecond !== 0)) return Number.NaN;\n\n\t\t// The year is taken literally: the format has no 1900s window for a\n\t\t// year from 0 to 99, unlike the constructor.\n\t\tconst wall = normaliseWallClock(year, month - 1, day, hour, minute, second, millisecond);\n\t\tif (zoneText === undefined && hourText !== undefined) {\n\t\t\t// A date-time with no offset is local time, by the format's own rule.\n\t\t\treturn this.resolve(wall);\n\t\t}\n\t\t// A date-only string is UTC midnight, and an offset is subtracted.\n\t\tlet offsetMinutes = 0;\n\t\tif (zoneText !== undefined && zoneText !== \"Z\" && zoneText !== \"z\") {\n\t\t\tconst digits = zoneText.slice(1).replace(\":\", \"\");\n\t\t\tconst offsetHours = Number(digits.slice(0, 2));\n\t\t\tconst offsetMinutesPart = Number(digits.slice(2, 4));\n\t\t\tif (offsetHours > 23 || offsetMinutesPart > 59) return Number.NaN;\n\t\t\toffsetMinutes = (zoneText[0] === \"-\" ? -1 : 1) * (offsetHours * 60 + offsetMinutesPart);\n\t\t}\n\t\tconst instant = wall.dayNumber * MS_PER_DAY + wall.timeOfDay - offsetMinutes * 60_000;\n\t\treturn Math.abs(instant) > MAX_INSTANT ? Number.NaN : instant;\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\tconst t = clip(epochMs);\n\t\t// `toLocaleDateString()` on an invalid date, rather than the throw\n\t\t// `Intl` would raise.\n\t\tif (Number.isNaN(t)) return \"Invalid Date\";\n\t\treturn new Intl.DateTimeFormat(locale, {\n\t\t\ttimeZone: this.timeZone, weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\",\n\t\t}).format(t);\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\tconst t = clip(epochMs);\n\t\tif (Number.isNaN(t)) return \"Invalid Date\";\n\t\t// `toLocaleTimeString()` with no options is the hour, minute and second\n\t\t// in the locale's own style.\n\t\treturn new Intl.DateTimeFormat(locale, {\n\t\t\ttimeZone: this.timeZone, hour: \"numeric\", minute: \"numeric\", second: \"numeric\",\n\t\t}).format(t);\n\t}\n\n\tzoneOffsetMinutes(zone: string, epochMs: number): number {\n\t\t// A fault here is the caller's to see, as the contract states, so no\n\t\t// clip: a non-finite instant reaches `Temporal` and throws its\n\t\t// RangeError, as an unknown zone does.\n\t\tconst t = Number.isFinite(epochMs) ? Math.trunc(epochMs) : epochMs;\n\t\tconst z = this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\t// The `Date` backend reads the zone's wall clock to the second and\n\t\t// rounds the difference from the instant to whole minutes; the same\n\t\t// arithmetic on the exact offset keeps the two answers identical for\n\t\t// the pre-standard-time offsets that are not whole minutes.\n\t\tconst wallSecond = Math.floor((t + z.offsetNanoseconds / 1e6) / 1000) * 1000;\n\t\treturn Math.round((wallSecond - epochMs) / 60_000) || 0;\n\t}\n\n\tfieldsInZone(zone: string, epochMs: number): ZonedFields {\n\t\tconst t = Number.isFinite(epochMs) ? Math.trunc(epochMs) : epochMs;\n\t\tconst z = this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\treturn { year: z.year, month0: z.month - 1, day: z.day, hour: z.hour, minute: z.minute, second: z.second };\n\t}\n\n\t/** The IANA zone this backend computes in, which is what `CalendarBackend.zone` documents. */\n\tzone(): string {\n\t\treturn this.timeZone;\n\t}\n\n\tformatTimeInZone(zone: string, epochMs: number): string {\n\t\treturn timeInZone(zone, epochMs);\n\t}\n\n\tformatDateInZone(zone: string, epochMs: number): string {\n\t\treturn dateInZone(zone, epochMs);\n\t}\n\n\t/** The zoned date-time of an instant, or `null` where `Date` would answer `NaN`. */\n\tprivate zoned(epochMs: number, zone: string): TemporalZonedDateTimeLike | null {\n\t\tconst t = clip(epochMs);\n\t\tif (Number.isNaN(t)) return null;\n\t\ttry {\n\t\t\treturn this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\t} catch {\n\t\t\t// Past the range the implementation represents in this zone.\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * The instant a set of local wall-clock fields names, with the fields\n\t * normalised the way `Date`'s constructor and setters normalise them\n\t * (month 12 is next January, day 0 the last of the month before, a year\n\t * from 0 to 99 the 1900s) before the zone is consulted.\n\t */\n\tprivate wallClock(year: number, month0: number, day: number, hour: number, minute: number, second: number, millisecond: number): number {\n\t\t// The constructor's two-digit-year window, applied to the year as\n\t\t// written and before any overflow, as `Date` applies it.\n\t\tconst windowed = year >= 0 && year <= 99 ? 1900 + Math.trunc(year) : year;\n\t\treturn this.resolve(normaliseWallClock(windowed, month0, day, hour, minute, second, millisecond));\n\t}\n\n\t/**\n\t * Normalised wall-clock fields resolved to an instant in the backend's\n\t * zone, clipped to the range `Date` represents only then, as `Date` clips\n\t * last. `compatible` disambiguation is `Date`'s rule: a time in a\n\t * spring-forward gap moves later by the gap, and a time that occurs twice\n\t * on a fall-back day is its first occurrence.\n\t */\n\tprivate resolve(wall: WallClock): number {\n\t\tconst civil = civilFromDayNumber(wall.dayNumber);\n\t\tif (Number.isNaN(civil.year)) return Number.NaN;\n\t\tconst hour = Math.floor(wall.timeOfDay / 3_600_000);\n\t\tconst minute = Math.floor(wall.timeOfDay / 60_000) % 60;\n\t\tconst second = Math.floor(wall.timeOfDay / 1_000) % 60;\n\t\tconst millisecond = wall.timeOfDay % 1_000;\n\t\ttry {\n\t\t\tconst plain = this.temporal.PlainDateTime.from(\n\t\t\t\t{ year: civil.year, month: civil.month0 + 1, day: civil.day, hour, minute, second, millisecond },\n\t\t\t\t{ overflow: \"reject\" },\n\t\t\t);\n\t\t\tconst instant = plain.toZonedDateTime(this.timeZone, { disambiguation: \"compatible\" }).epochMilliseconds;\n\t\t\treturn Math.abs(instant) > MAX_INSTANT ? Number.NaN : instant;\n\t\t} catch {\n\t\t\t// Past the range the implementation represents: `Date` answers NaN.\n\t\t\treturn Number.NaN;\n\t\t}\n\t}\n}\n\n/** Refuse anything that is not a usable `Temporal` before a method can fail on it obscurely. */\nfunction assertTemporalLike(temporal: unknown): asserts temporal is TemporalLike {\n\tconst candidate = temporal as Partial<TemporalLike> | null | undefined;\n\tconst missing =\n\t\ttypeof candidate?.Now?.instant !== \"function\" ? \"Now.instant\" :\n\t\ttypeof candidate?.Now?.timeZoneId !== \"function\" ? \"Now.timeZoneId\" :\n\t\ttypeof candidate?.Instant?.fromEpochMilliseconds !== \"function\" ? \"Instant.fromEpochMilliseconds\" :\n\t\ttypeof candidate?.PlainDateTime?.from !== \"function\" ? \"PlainDateTime.from\" :\n\t\tnull;\n\tif (missing !== null) {\n\t\tthrow ErrorFactory.config(\n\t\t\tCoreErrorCodes.TEMPORAL_IMPLEMENTATION_INVALID,\n\t\t\t`createTemporalCalendar needs a Temporal implementation (globalThis.Temporal on a runtime that ships it, or a polyfill's export); the value given has no ${missing}`,\n\t\t\t{ missing },\n\t\t);\n\t}\n}\n\n/**\n * A calendar backend over the host's `Temporal`, for the engine's `calendar`\n * option.\n *\n * ```ts\n * import { createEngine } from \"solve-engine\";\n * import { createTemporalCalendar } from \"solve-engine/temporal\";\n *\n * const calendar = createTemporalCalendar(globalThis.Temporal, { timeZone: \"Asia/Tokyo\" });\n * const engine = createEngine({ calendar });\n * ```\n *\n * @param temporal - The `Temporal` implementation: `globalThis.Temporal` where the runtime ships one, or a polyfill's export.\n * @param options - The zone to compute in and, for a test, the clock to read; see {@link TemporalCalendarOptions}.\n * @returns A backend that computes every date in that zone and answers what the `Date` backend would in it.\n * @throws `TEMPORAL_IMPLEMENTATION_INVALID` when `temporal` lacks the members the backend uses, and\n * `TEMPORAL_TIME_ZONE_UNKNOWN` when the implementation does not know the zone asked for.\n */\nexport function createTemporalCalendar(temporal: TemporalLike, options: TemporalCalendarOptions = {}): TemporalCalendar {\n\treturn new TemporalCalendar(temporal, options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/temporal/CivilDays.ts","../src/temporal/TemporalCalendar.ts"],"names":["civilDayNumber","year","month0","day","y0","m0","d","y","m","shiftedYear","era","yearOfEra","dayOfYear","dayOfEra","civilFromDayNumber","days","z","monthFromMarch","month","NAN_FIELDS","MAX_INSTANT","MS_PER_DAY","clip","epochMs","normaliseWallClock","hour","minute","second","millisecond","time","ISO_DATE_TIME","TemporalCalendar","temporal","options","assertTemporalLike","requested","probe","error","ErrorFactory","CoreErrorCodes","minutesPastMidnight","anchored","a","f","months","f0","dayOfMonth","f1","f2","daysInMonth","text","yearText","monthText","dayText","hourText","minuteText","secondText","fractionText","zoneText","wall","offsetMinutes","digits","offsetHours","offsetMinutesPart","instant","locale","t","zone","wallSecond","timeInZone","dateInZone","windowed","civil","candidate","missing","createTemporalCalendar"],"mappings":"8EAkDO,SAASA,EAAeC,CAAAA,CAAcC,CAAAA,CAAgBC,CAAAA,CAAqB,CACjF,IAAMC,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAMH,CAAI,EACpBI,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAMH,CAAM,EACtBI,CAAAA,CAAI,IAAA,CAAK,KAAA,CAAMH,CAAG,EACxB,GAAI,CAAC,MAAA,CAAO,QAAA,CAASC,CAAE,CAAA,EAAK,CAAC,MAAA,CAAO,QAAA,CAASC,CAAE,CAAA,EAAK,CAAC,OAAO,QAAA,CAASC,CAAC,EAAG,OAAO,MAAA,CAAO,GAAA,CAGvF,IAAMC,EAAIH,CAAAA,CAAK,IAAA,CAAK,KAAA,CAAMC,CAAAA,CAAK,EAAE,CAAA,CAC3BG,CAAAA,CAAAA,CAAMH,CAAAA,CAAK,EAAA,CAAM,IAAM,EAAA,CAAK,CAAA,CAG5BI,EAAcF,CAAAA,EAAKC,CAAAA,EAAK,EAAI,CAAA,CAAI,CAAA,CAAA,CAChCE,CAAAA,CAAM,IAAA,CAAK,MAAMD,CAAAA,CAAc,GAAG,CAAA,CAClCE,CAAAA,CAAYF,EAAcC,CAAAA,CAAM,GAAA,CAChCE,CAAAA,CAAY,IAAA,CAAK,OAAO,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,IAAA,CAAK,GAAA,CAAIoC,CAAO,EAAI5C,CAAAA,CAAc,MAAA,CAAO,GAAA,CAAM4C,CACvD,MAAQ,CAEP,OAAO,OAAO,GACf,CACD,CACD,EAGA,SAAS9B,CAAAA,CAAmBF,CAAAA,CAAqD,CAChF,IAAMyC,CAAAA,CAAYzC,CAAAA,CACZ0C,CAAAA,CACL,OAAOD,CAAAA,EAAW,GAAA,EAAK,OAAA,EAAY,UAAA,CAAa,cAChD,OAAOA,CAAAA,EAAW,KAAK,UAAA,EAAe,UAAA,CAAa,iBACnD,OAAOA,CAAAA,EAAW,OAAA,EAAS,qBAAA,EAA0B,WAAa,+BAAA,CAClE,OAAOA,CAAAA,EAAW,aAAA,EAAe,MAAS,UAAA,CAAa,oBAAA,CACvD,IAAA,CACD,GAAIC,IAAY,IAAA,CACf,MAAMpC,EAAa,MAAA,CAClBC,CAAAA,CAAe,gCACf,CAAA,wJAAA,EAA2JmC,CAAO,CAAA,CAAA,CAClK,CAAE,QAAAA,CAAQ,CACX,CAEF,CAoBO,SAASC,CAAAA,CAAuB3C,CAAAA,CAAwBC,CAAAA,CAAmC,GAAsB,CACvH,OAAO,IAAIF,CAAAA,CAAiBC,CAAAA,CAAUC,CAAO,CAC9C","file":"chunk-I6WGOM3C.js","sourcesContent":["/**\n * The day arithmetic behind `Date`'s field normalisation, for the `Temporal`\n * backend.\n *\n * `Date` normalises a set of wall-clock fields before it resolves them in a\n * zone: month 13 rolls into the next year, day 0 into the month before, a\n * time past midnight into the next day, and only the final instant is\n * clipped to the range `Date` represents. That is the `MakeDay` and\n * `MakeTime` order of the ECMAScript specification, and a backend built on\n * another library has to follow it to answer what `Date` answers on the last\n * representable day and for a rolled-over literal. `Date` does this\n * arithmetic inside its own setters, where a second backend cannot reach it,\n * so it is written out here with nothing clipped.\n *\n * Under `temporal/` rather than `calendar/Gregorian.ts` because only the\n * `Temporal` backend needs it: the `Date` backend gets the same arithmetic\n * from `Date` itself, and keeping it here keeps it out of the root entry's\n * bundle. The unit spec measures it against `Date.UTC` and `setUTCFullYear`\n * wherever `Date` can represent the date.\n *\n * @module CivilDays\n */\n\n/** A calendar date as year, zero-based month and day, the shape the civil-day arithmetic exchanges. */\nexport interface CivilDate {\n\treadonly year: number;\n\t/** Zero-based month: 0 is January, 11 is December. */\n\treadonly month0: number;\n\t/** Day of the month, from 1. */\n\treadonly day: number;\n}\n\n/**\n * The day number of a calendar date, counted from 1 January 1970, by\n * arithmetic alone: no `Date`, so no clip to the range `Date` represents.\n *\n * This is the `MakeDay` step of the ECMAScript specification, which a\n * backend needs unclipped: `Date` normalises a set of fields (month 13, day\n * 0, a time past midnight) before it resolves them in a zone and clips the\n * result, so a wall-clock time on the last representable day is an instant,\n * not `NaN`, and a backend built on another library must follow the same\n * order. An overflowing month or day rolls into the adjacent year or month,\n * as {@link utcMs}'s do, and a fractional field is truncated, as `Date`\n * truncates it.\n *\n * @param year - The calendar year, read as written.\n * @param month0 - Zero-based month; overflow rolls into the adjacent year.\n * @param day - Day of the month; overflow rolls into the adjacent month.\n * @returns Whole days since 1 January 1970, negative before it, or `NaN` when a field is not finite.\n */\nexport function civilDayNumber(year: number, month0: number, day: number): number {\n\tconst y0 = Math.trunc(year);\n\tconst m0 = Math.trunc(month0);\n\tconst d = Math.trunc(day);\n\tif (!Number.isFinite(y0) || !Number.isFinite(m0) || !Number.isFinite(d)) return Number.NaN;\n\t// Normalise the month into the year first, then count from the first of\n\t// that month, so a day of 0 or 40 is a plain offset from a real month.\n\tconst y = y0 + Math.floor(m0 / 12);\n\tconst m = ((m0 % 12) + 12) % 12 + 1;\n\t// The days-from-civil arithmetic, with the year taken to start in March\n\t// so a leap day is the last day of the cycle rather than an exception.\n\tconst shiftedYear = y - (m <= 2 ? 1 : 0);\n\tconst era = Math.floor(shiftedYear / 400);\n\tconst yearOfEra = shiftedYear - era * 400;\n\tconst dayOfYear = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5);\n\tconst dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;\n\treturn era * 146_097 + dayOfEra - 719_468 + (d - 1);\n}\n\n/**\n * The calendar date of a day number, the inverse of {@link civilDayNumber}.\n *\n * @param days - Whole days since 1 January 1970, negative before it.\n * @returns The date, or `NaN` in every field when `days` is not finite.\n */\nexport function civilFromDayNumber(days: number): CivilDate {\n\tif (!Number.isFinite(days)) return { year: Number.NaN, month0: Number.NaN, day: Number.NaN };\n\tconst z = Math.trunc(days) + 719_468;\n\tconst era = Math.floor(z / 146_097);\n\tconst dayOfEra = z - era * 146_097;\n\tconst yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36_524) - Math.floor(dayOfEra / 146_096)) / 365);\n\tconst dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));\n\tconst monthFromMarch = Math.floor((5 * dayOfYear + 2) / 153);\n\tconst day = dayOfYear - Math.floor((153 * monthFromMarch + 2) / 5) + 1;\n\tconst month = monthFromMarch < 10 ? monthFromMarch + 3 : monthFromMarch - 9;\n\tconst year = yearOfEra + era * 400 + (month <= 2 ? 1 : 0);\n\treturn { year, month0: month - 1, day };\n}\n","/**\n * The `Temporal` calendar backend: the engine's date questions answered\n * through a `Temporal` implementation the host supplies, in a time zone the\n * host chooses.\n *\n * `Temporal` is the JavaScript standard library's replacement for `Date`. It\n * ships unflagged in Node 26 and in current Chrome, Firefox and Deno, but not\n * in Safari nor in Node 22 and 24, and the smallest polyfill adds about twenty\n * kilobytes gzipped to a bundle. The engine therefore imports no `Temporal`\n * and no polyfill: this module is reached only through the\n * `solve-engine/temporal` entry, and the host hands it the implementation to\n * use, `globalThis.Temporal` on a runtime that has one or a polyfill's export.\n * A host that never imports the entry pays nothing for it.\n *\n * The backend answers exactly what the `Date` backend answers. That is a\n * design constraint rather than a hope: `Temporal` and `Date` differ in what\n * they do with an out-of-range instant (`RangeError` against `NaN`), a\n * fractional millisecond (a throw against truncation), a day past the end of\n * a month (a clamp or a throw against a roll into the next month) and a year\n * from 0 to 99 (read literally against read as the 1900s), and every one of\n * those is reproduced here the way `Date` does it, because the engine's\n * results are measured against `Date` and a host switching backends must see\n * no result move. The differential suite under `__tests__/temporal/` is what\n * holds that line.\n *\n * The one thing that does change is the zone. `Date` reads the process's own\n * zone and nothing else; this backend reads the zone it was constructed with,\n * so a document can be computed in Tokyo from a server in London, or in a\n * zone the reader picks. That is the capability the backend adds, and the\n * only observable difference.\n *\n * The named-zone display strings go through the same `Intl.DateTimeFormat`\n * helpers the `Date` backend uses (`calendar/IntlZone.ts`), and the zone-free\n * arithmetic through `calendar/Gregorian.ts`, so the two backends share one\n * implementation wherever an answer does not depend on which backend is in\n * use. The one piece of arithmetic `Date` keeps inside its own setters, the\n * normalisation of overflowing fields, is written out in `CivilDays.ts`.\n *\n * @module TemporalCalendar\n */\n\nimport type { CalendarBackend, CalendarFields, ZonedFields } from \"@solve-js/calendar/CalendarBackend\";\nimport { daysInMonth } from \"@solve-js/calendar/Gregorian\";\nimport { civilDayNumber, civilFromDayNumber } from \"./CivilDays\";\nimport { dateInZone, timeInZone } from \"@solve-js/calendar/IntlZone\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { CoreErrorCodes } from \"@solve-js/errors/ErrorCode\";\n\n/**\n * The part of a `Temporal.Instant` the backend reads: its epoch milliseconds,\n * and the zoned date-time it shows in a named zone.\n */\nexport interface TemporalInstantLike {\n\treadonly epochMilliseconds: number;\n\ttoZonedDateTimeISO(timeZone: string): TemporalZonedDateTimeLike;\n}\n\n/**\n * The part of a `Temporal.ZonedDateTime` the backend reads: the calendar\n * fields (a one-based month and an ISO weekday, Monday 1 to Sunday 7, both\n * translated at the boundary), the offset, and the instant.\n */\nexport interface TemporalZonedDateTimeLike {\n\treadonly year: number;\n\t/** One-based month, 1 is January, as `Temporal` counts. */\n\treadonly month: number;\n\treadonly day: number;\n\t/** ISO weekday: Monday is 1, Sunday is 7. */\n\treadonly dayOfWeek: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly second: number;\n\treadonly millisecond: number;\n\t/** The zone's offset from UTC at this instant, in nanoseconds, positive when ahead. */\n\treadonly offsetNanoseconds: number;\n\treadonly epochMilliseconds: number;\n\t/** The zone's canonical IANA identifier. */\n\treadonly timeZoneId: string;\n}\n\n/** The part of a `Temporal.PlainDateTime` the backend uses: resolving a wall-clock time to an instant in a zone. */\nexport interface TemporalPlainDateTimeLike {\n\ttoZonedDateTime(\n\t\ttimeZone: string,\n\t\toptions?: { disambiguation?: \"compatible\" | \"earlier\" | \"later\" | \"reject\" },\n\t): TemporalZonedDateTimeLike;\n}\n\n/** The wall-clock fields a `Temporal.PlainDateTime` is built from, with a one-based month. */\nexport interface TemporalDateTimeFields {\n\tyear: number;\n\t/** One-based month, 1 is January. */\n\tmonth: number;\n\tday: number;\n\thour: number;\n\tminute: number;\n\tsecond: number;\n\tmillisecond: number;\n}\n\n/**\n * The subset of the `Temporal` namespace the backend uses, as a structural\n * type, so the engine compiles and ships with no `Temporal` type installed\n * and a host passes whichever implementation it has: `globalThis.Temporal`\n * on Node 26 or a current browser, or the export of a polyfill such as\n * `temporal-polyfill`. Both satisfy this shape as they are.\n */\nexport interface TemporalLike {\n\treadonly Now: {\n\t\tinstant(): TemporalInstantLike;\n\t\ttimeZoneId(): string;\n\t};\n\treadonly Instant: {\n\t\tfromEpochMilliseconds(epochMilliseconds: number): TemporalInstantLike;\n\t};\n\treadonly PlainDateTime: {\n\t\tfrom(fields: TemporalDateTimeFields, options?: { overflow?: \"constrain\" | \"reject\" }): TemporalPlainDateTimeLike;\n\t};\n}\n\n/** What {@link createTemporalCalendar} takes beside the implementation. */\nexport interface TemporalCalendarOptions {\n\t/**\n\t * The IANA time zone the engine computes dates in (`\"Asia/Tokyo\"`,\n\t * `\"UTC\"`). Defaults to the runtime's own zone, `Temporal.Now.timeZoneId()`,\n\t * which is what the `Date` backend reads. A zone the implementation does\n\t * not know is refused at construction with `TEMPORAL_TIME_ZONE_UNKNOWN`.\n\t */\n\ttimeZone?: string;\n\t/**\n\t * The clock `now()` reads, in epoch milliseconds. Defaults to\n\t * `Temporal.Now.instant()`. A test pins a date with this: a fake-timer\n\t * library replaces `Date.now`, which the `Date` backend reads, but not\n\t * `Temporal.Now`, so this backend needs telling separately.\n\t */\n\tnow?: () => number;\n}\n\n/** The fields the `Date` backend answers for an instant it cannot represent. */\nconst NAN_FIELDS: CalendarFields = Object.freeze({\n\tyear: Number.NaN, month0: Number.NaN, day: Number.NaN, weekday: Number.NaN,\n\thour: Number.NaN, minute: Number.NaN, second: Number.NaN, millisecond: Number.NaN,\n});\n\n/** The largest magnitude `Date` represents, in milliseconds either side of the epoch. */\nconst MAX_INSTANT = 8.64e15;\n\n/** Milliseconds in a day of wall-clock fields, before any zone is consulted. */\nconst MS_PER_DAY = 86_400_000;\n\n/**\n * An instant as `Date` would hold it: truncated to a whole millisecond, or\n * `NaN` when it is not finite or lies past the range `Date` represents. This\n * is `Date`'s own clip (its `TimeClip`), applied before an instant reaches\n * `Temporal`, which throws for both cases where `Date` answers `NaN`.\n */\nfunction clip(epochMs: number): number {\n\tif (!Number.isFinite(epochMs) || Math.abs(epochMs) > MAX_INSTANT) return Number.NaN;\n\treturn Math.trunc(epochMs);\n}\n\n/**\n * Wall-clock fields normalised the way `Date`'s `MakeDay` and `MakeTime`\n * normalise them, with nothing clipped: the day number of the date the\n * fields land on after any overflow rolls, and the time within that day.\n * Each field is truncated to an integer first, as `Date` truncates it.\n */\ninterface WallClock {\n\treadonly dayNumber: number;\n\treadonly timeOfDay: number;\n}\n\n/** `MakeDay` and `MakeTime`, then `MakeDate`, with a time past midnight carried into the day. */\nfunction normaliseWallClock(year: number, month0: number, day: number, hour: number, minute: number, second: number, millisecond: number): WallClock {\n\tconst time = Math.trunc(hour) * 3_600_000 + Math.trunc(minute) * 60_000 + Math.trunc(second) * 1_000 + Math.trunc(millisecond);\n\tconst dayNumber = civilDayNumber(year, month0, day) + Math.floor(time / MS_PER_DAY);\n\treturn { dayNumber, timeOfDay: ((time % MS_PER_DAY) + MS_PER_DAY) % MS_PER_DAY };\n}\n\n/**\n * The ECMAScript date-time string format, as the `Date` constructor reads it:\n * a four-digit or six-digit signed year, an optional month and day, an\n * optional time to the millisecond (longer fractions are truncated), and an\n * optional `Z` or offset. The `T` and `Z` may be lower case, and an offset\n * may omit its colon; both are what the runtime's parser accepts.\n */\nconst ISO_DATE_TIME =\n\t/^([+-]\\d{6}|\\d{4})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:[Tt](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?)?([Zz]|[+-]\\d{2}:?\\d{2})?$/;\n\n/**\n * A {@link CalendarBackend} over a `Temporal` implementation, computing in\n * one named time zone. Build one with {@link createTemporalCalendar}.\n *\n * Every method answers what the `Date` backend answers for the same inputs\n * when the zone is the process's own; see the module comment for the\n * differences between `Temporal` and `Date` that are reproduced deliberately.\n * The local methods answer `NaN` for an instant or a date the backend cannot\n * represent and never throw; the four named-zone methods throw the runtime's\n * `RangeError` for a zone it does not know or an instant it cannot represent,\n * which is the contract the interface states.\n */\nexport class TemporalCalendar implements CalendarBackend {\n\t/** The IANA zone every local answer is computed in, in its canonical spelling. */\n\treadonly timeZone: string;\n\n\tprivate readonly temporal: TemporalLike;\n\tprivate readonly clock: () => number;\n\n\tconstructor(temporal: TemporalLike, options: TemporalCalendarOptions = {}) {\n\t\tassertTemporalLike(temporal);\n\t\tthis.temporal = temporal;\n\t\tconst requested = options.timeZone ?? temporal.Now.timeZoneId();\n\t\tlet probe: TemporalZonedDateTimeLike;\n\t\ttry {\n\t\t\tprobe = temporal.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(requested);\n\t\t} catch (error) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tCoreErrorCodes.TEMPORAL_TIME_ZONE_UNKNOWN,\n\t\t\t\t`The Temporal implementation does not know the time zone \"${requested}\"`,\n\t\t\t\t{ timeZone: requested, cause: error instanceof Error ? error.message : String(error) },\n\t\t\t);\n\t\t}\n\t\t// The canonical spelling, so a zone given as `asia/tokyo` reads back as\n\t\t// the identifier the implementation itself uses.\n\t\tthis.timeZone = probe.timeZoneId;\n\t\tthis.clock = options.now ?? (() => temporal.Now.instant().epochMilliseconds);\n\t}\n\n\tnow(): number {\n\t\treturn this.clock();\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst z = this.zoned(epochMs, this.timeZone);\n\t\tif (z === null) return NAN_FIELDS;\n\t\treturn {\n\t\t\tyear: z.year,\n\t\t\tmonth0: z.month - 1,\n\t\t\tday: z.day,\n\t\t\t// ISO's Monday 1 to Sunday 7 becomes Date's Sunday 0 to Saturday 6.\n\t\t\tweekday: z.dayOfWeek % 7,\n\t\t\thour: z.hour,\n\t\t\tminute: z.minute,\n\t\t\tsecond: z.second,\n\t\t\tmillisecond: z.millisecond,\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn this.wallClock(year, month0, day, 0, 0, 0, 0);\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// `Date`'s sequence exactly: anchor at midnight, then set the minutes\n\t\t// FIELD, which reads the hour, second and millisecond back from the\n\t\t// anchored local time. On a day whose midnight falls in a\n\t\t// daylight-saving gap the anchor resolves to 1 am, and the hour it\n\t\t// reads back is 1, which is what makes the two backends agree there.\n\t\tconst anchored = this.localMidnight(year, month0, day);\n\t\tconst a = this.fields(anchored);\n\t\tif (Number.isNaN(a.year)) return Number.NaN;\n\t\treturn this.wallClock(a.year, a.month0, a.day, a.hour, minutesPastMidnight, a.second, a.millisecond);\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\t// `setDate()`: the day field moves and the local time of day is held.\n\t\tconst f = this.fields(epochMs);\n\t\tif (Number.isNaN(f.year)) return Number.NaN;\n\t\treturn this.wallClock(f.year, f.month0, f.day + days, f.hour, f.minute, f.second, f.millisecond);\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\t// The `Date` backend's three field writes, each resolved to an instant\n\t\t// and read back before the next, so that a wall-clock time landing in\n\t\t// a transition on an intermediate date shifts the same way it does\n\t\t// there: park on the 1st, move the month, then clamp the day.\n\t\tconst f0 = this.fields(epochMs);\n\t\tif (Number.isNaN(f0.year)) return Number.NaN;\n\t\tconst dayOfMonth = f0.day;\n\t\tconst f1 = this.fields(this.wallClock(f0.year, f0.month0, 1, f0.hour, f0.minute, f0.second, f0.millisecond));\n\t\tif (Number.isNaN(f1.year)) return Number.NaN;\n\t\tconst f2 = this.fields(this.wallClock(f1.year, f1.month0 + months, f1.day, f1.hour, f1.minute, f1.second, f1.millisecond));\n\t\tif (Number.isNaN(f2.year)) return Number.NaN;\n\t\tconst day = Math.min(dayOfMonth, daysInMonth(f2.year, f2.month0));\n\t\treturn this.wallClock(f2.year, f2.month0, day, f2.hour, f2.minute, f2.second, f2.millisecond);\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\tconst z = this.zoned(epochMs, this.timeZone);\n\t\tif (z === null) return Number.NaN;\n\t\t// `getTimezoneOffset()` answers whole minutes, truncated toward zero,\n\t\t// which only shows for the local-mean-time offsets in force before a\n\t\t// zone adopted standard time (London's was -00:01:15 until 1847).\n\t\t// `|| 0` folds the -0 a small negative offset truncates to.\n\t\treturn Math.trunc(z.offsetNanoseconds / 60_000_000_000) || 0;\n\t}\n\n\tparseIso8601(text: string): number {\n\t\t// Only the format itself. The `Date` constructor falls back to a\n\t\t// legacy parser for a string the format rejects (one with a space\n\t\t// around it, say) and may guess an instant from it; the engine's own\n\t\t// gate admits only the format, so the two backends cannot disagree\n\t\t// through it, and outside it this backend answers NaN rather than guess.\n\t\tconst m = ISO_DATE_TIME.exec(text);\n\t\tif (m === null) return Number.NaN;\n\t\tconst [, yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, zoneText] = m;\n\t\t// An expanded year of `-000000` names no year, by the format's own rule.\n\t\tif (yearText === \"-000000\") return Number.NaN;\n\t\tconst year = Number(yearText);\n\t\tconst month = monthText === undefined ? 1 : Number(monthText);\n\t\tconst day = dayText === undefined ? 1 : Number(dayText);\n\t\tconst hour = hourText === undefined ? 0 : Number(hourText);\n\t\tconst minute = minuteText === undefined ? 0 : Number(minuteText);\n\t\tconst second = secondText === undefined ? 0 : Number(secondText);\n\t\t// Only the first three digits of a fraction are milliseconds; the rest\n\t\t// are dropped rather than rounded, as the runtime's parser does.\n\t\tconst millisecond = fractionText === undefined ? 0 : Number(fractionText.slice(0, 3).padEnd(3, \"0\"));\n\t\t// The runtime checks a day against 31, not against the month, and lets\n\t\t// 30 February roll into March; 24:00 is the end of the day and nothing\n\t\t// past it is a time.\n\t\tif (month < 1 || month > 12 || day < 1 || day > 31) return Number.NaN;\n\t\tif (hour > 24 || minute > 59 || second > 59) return Number.NaN;\n\t\tif (hour === 24 && (minute !== 0 || second !== 0 || millisecond !== 0)) return Number.NaN;\n\n\t\t// The year is taken literally: the format has no 1900s window for a\n\t\t// year from 0 to 99, unlike the constructor.\n\t\tconst wall = normaliseWallClock(year, month - 1, day, hour, minute, second, millisecond);\n\t\tif (zoneText === undefined && hourText !== undefined) {\n\t\t\t// A date-time with no offset is local time, by the format's own rule.\n\t\t\treturn this.resolve(wall);\n\t\t}\n\t\t// A date-only string is UTC midnight, and an offset is subtracted.\n\t\tlet offsetMinutes = 0;\n\t\tif (zoneText !== undefined && zoneText !== \"Z\" && zoneText !== \"z\") {\n\t\t\tconst digits = zoneText.slice(1).replace(\":\", \"\");\n\t\t\tconst offsetHours = Number(digits.slice(0, 2));\n\t\t\tconst offsetMinutesPart = Number(digits.slice(2, 4));\n\t\t\tif (offsetHours > 23 || offsetMinutesPart > 59) return Number.NaN;\n\t\t\toffsetMinutes = (zoneText[0] === \"-\" ? -1 : 1) * (offsetHours * 60 + offsetMinutesPart);\n\t\t}\n\t\tconst instant = wall.dayNumber * MS_PER_DAY + wall.timeOfDay - offsetMinutes * 60_000;\n\t\treturn Math.abs(instant) > MAX_INSTANT ? Number.NaN : instant;\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\tconst t = clip(epochMs);\n\t\t// `toLocaleDateString()` on an invalid date, rather than the throw\n\t\t// `Intl` would raise.\n\t\tif (Number.isNaN(t)) return \"Invalid Date\";\n\t\treturn new Intl.DateTimeFormat(locale, {\n\t\t\ttimeZone: this.timeZone, weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\",\n\t\t}).format(t);\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\tconst t = clip(epochMs);\n\t\tif (Number.isNaN(t)) return \"Invalid Date\";\n\t\t// `toLocaleTimeString()` with no options is the hour, minute and second\n\t\t// in the locale's own style.\n\t\treturn new Intl.DateTimeFormat(locale, {\n\t\t\ttimeZone: this.timeZone, hour: \"numeric\", minute: \"numeric\", second: \"numeric\",\n\t\t}).format(t);\n\t}\n\n\tzoneOffsetMinutes(zone: string, epochMs: number): number {\n\t\t// A fault here is the caller's to see, as the contract states, so no\n\t\t// clip: a non-finite instant reaches `Temporal` and throws its\n\t\t// RangeError, as an unknown zone does.\n\t\tconst t = Number.isFinite(epochMs) ? Math.trunc(epochMs) : epochMs;\n\t\tconst z = this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\t// The `Date` backend reads the zone's wall clock to the second and\n\t\t// rounds the difference from the instant to whole minutes; the same\n\t\t// arithmetic on the exact offset keeps the two answers identical for\n\t\t// the pre-standard-time offsets that are not whole minutes.\n\t\tconst wallSecond = Math.floor((t + z.offsetNanoseconds / 1e6) / 1000) * 1000;\n\t\treturn Math.round((wallSecond - epochMs) / 60_000) || 0;\n\t}\n\n\tfieldsInZone(zone: string, epochMs: number): ZonedFields {\n\t\tconst t = Number.isFinite(epochMs) ? Math.trunc(epochMs) : epochMs;\n\t\tconst z = this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\treturn { year: z.year, month0: z.month - 1, day: z.day, hour: z.hour, minute: z.minute, second: z.second };\n\t}\n\n\t/** The IANA zone this backend computes in, which is what `CalendarBackend.zone` documents. */\n\tzone(): string {\n\t\treturn this.timeZone;\n\t}\n\n\tformatTimeInZone(zone: string, epochMs: number): string {\n\t\treturn timeInZone(zone, epochMs);\n\t}\n\n\tformatDateInZone(zone: string, epochMs: number): string {\n\t\treturn dateInZone(zone, epochMs);\n\t}\n\n\t/** The zoned date-time of an instant, or `null` where `Date` would answer `NaN`. */\n\tprivate zoned(epochMs: number, zone: string): TemporalZonedDateTimeLike | null {\n\t\tconst t = clip(epochMs);\n\t\tif (Number.isNaN(t)) return null;\n\t\ttry {\n\t\t\treturn this.temporal.Instant.fromEpochMilliseconds(t).toZonedDateTimeISO(zone);\n\t\t} catch {\n\t\t\t// Past the range the implementation represents in this zone.\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * The instant a set of local wall-clock fields names, with the fields\n\t * normalised the way `Date`'s constructor and setters normalise them\n\t * (month 12 is next January, day 0 the last of the month before, a year\n\t * from 0 to 99 the 1900s) before the zone is consulted.\n\t */\n\tprivate wallClock(year: number, month0: number, day: number, hour: number, minute: number, second: number, millisecond: number): number {\n\t\t// The constructor's two-digit-year window, applied to the year as\n\t\t// written and before any overflow, as `Date` applies it.\n\t\tconst windowed = year >= 0 && year <= 99 ? 1900 + Math.trunc(year) : year;\n\t\treturn this.resolve(normaliseWallClock(windowed, month0, day, hour, minute, second, millisecond));\n\t}\n\n\t/**\n\t * Normalised wall-clock fields resolved to an instant in the backend's\n\t * zone, clipped to the range `Date` represents only then, as `Date` clips\n\t * last. `compatible` disambiguation is `Date`'s rule: a time in a\n\t * spring-forward gap moves later by the gap, and a time that occurs twice\n\t * on a fall-back day is its first occurrence.\n\t */\n\tprivate resolve(wall: WallClock): number {\n\t\tconst civil = civilFromDayNumber(wall.dayNumber);\n\t\tif (Number.isNaN(civil.year)) return Number.NaN;\n\t\tconst hour = Math.floor(wall.timeOfDay / 3_600_000);\n\t\tconst minute = Math.floor(wall.timeOfDay / 60_000) % 60;\n\t\tconst second = Math.floor(wall.timeOfDay / 1_000) % 60;\n\t\tconst millisecond = wall.timeOfDay % 1_000;\n\t\ttry {\n\t\t\tconst plain = this.temporal.PlainDateTime.from(\n\t\t\t\t{ year: civil.year, month: civil.month0 + 1, day: civil.day, hour, minute, second, millisecond },\n\t\t\t\t{ overflow: \"reject\" },\n\t\t\t);\n\t\t\tconst instant = plain.toZonedDateTime(this.timeZone, { disambiguation: \"compatible\" }).epochMilliseconds;\n\t\t\treturn Math.abs(instant) > MAX_INSTANT ? Number.NaN : instant;\n\t\t} catch {\n\t\t\t// Past the range the implementation represents: `Date` answers NaN.\n\t\t\treturn Number.NaN;\n\t\t}\n\t}\n}\n\n/** Refuse anything that is not a usable `Temporal` before a method can fail on it obscurely. */\nfunction assertTemporalLike(temporal: unknown): asserts temporal is TemporalLike {\n\tconst candidate = temporal as Partial<TemporalLike> | null | undefined;\n\tconst missing =\n\t\ttypeof candidate?.Now?.instant !== \"function\" ? \"Now.instant\" :\n\t\ttypeof candidate?.Now?.timeZoneId !== \"function\" ? \"Now.timeZoneId\" :\n\t\ttypeof candidate?.Instant?.fromEpochMilliseconds !== \"function\" ? \"Instant.fromEpochMilliseconds\" :\n\t\ttypeof candidate?.PlainDateTime?.from !== \"function\" ? \"PlainDateTime.from\" :\n\t\tnull;\n\tif (missing !== null) {\n\t\tthrow ErrorFactory.config(\n\t\t\tCoreErrorCodes.TEMPORAL_IMPLEMENTATION_INVALID,\n\t\t\t`createTemporalCalendar needs a Temporal implementation (globalThis.Temporal on a runtime that ships it, or a polyfill's export); the value given has no ${missing}`,\n\t\t\t{ missing },\n\t\t);\n\t}\n}\n\n/**\n * A calendar backend over the host's `Temporal`, for the engine's `calendar`\n * option.\n *\n * ```ts\n * import { createEngine } from \"solve-engine\";\n * import { createTemporalCalendar } from \"solve-engine/temporal\";\n *\n * const calendar = createTemporalCalendar(globalThis.Temporal, { timeZone: \"Asia/Tokyo\" });\n * const engine = createEngine({ calendar });\n * ```\n *\n * @param temporal - The `Temporal` implementation: `globalThis.Temporal` where the runtime ships one, or a polyfill's export.\n * @param options - The zone to compute in and, for a test, the clock to read; see {@link TemporalCalendarOptions}.\n * @returns A backend that computes every date in that zone and answers what the `Date` backend would in it.\n * @throws `TEMPORAL_IMPLEMENTATION_INVALID` when `temporal` lacks the members the backend uses, and\n * `TEMPORAL_TIME_ZONE_UNKNOWN` when the implementation does not know the zone asked for.\n */\nexport function createTemporalCalendar(temporal: TemporalLike, options: TemporalCalendarOptions = {}): TemporalCalendar {\n\treturn new TemporalCalendar(temporal, options);\n}\n"]}
|